简体   繁体   English

如何使用 JavaScript(html 脚本)将 JWT-TOKEN 传递给 localStorage?

[英]How to pass JWT-TOKEN to localStorage using JavaScript (script for html)?

I am writing a Rest MVC application for an online coffee and tea store.我正在为一家在线咖啡和茶店编写Rest MVC应用程序。 The following technologies are used: Spring-Boot , Hibernate , PostgreSQL , Gradle , Thymeleaf , HTML , CSS .使用了以下技术: Spring-BootHibernatePostgreSQLGradleThymeleafHTMLCSS I have the whole backend ready, it remains to make a frontend.我已经准备好了整个后端,剩下的就是制作一个前端。 At the moment I'm making an authorization page.目前我正在制作授权页面。 The page itself is ready with HTML and CSS , now you need to make the authorization logic itself.页面本身已准备好HTMLCSS ,现在您需要自己制作授权逻辑。 To do this, I need to write a script in javascript so that my jwt token is stored in localStorage .为此,我需要用javascript编写一个脚本,以便我的jwt token存储在localStorage The point is that I don't know how to implement this, how to pass my token through the header using javascripte in localStorage .关键是我不知道如何实现这一点,如何在localStorage使用javascripte通过标头传递我的token

Important: javascript must be clean, without using frameworks ( angular , node ...).重要提示: javascript必须干净,不使用框架( angularnode ...)。 How should I do it?我该怎么做?

PS Again, the whole backand is ready. PS再次,整个backand准备好了。 Rest -authorization method works (that is, I enter my login and password - I get a jwt token ). Rest -authorization 方法有效(也就是说,我输入我的loginpassword - 我得到一个jwt token )。

在此处输入图片说明

Java - authorization method Java - 授权方法

 public ResponseEntity<Map<String, String>> authorization(@RequestBody AuthenticationRequestDTO requestDto) {
        try {
            String login = requestDto.getLogin();
            authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(login, requestDto.getPassword()));

            User user = userRepository.getByLogin(login);

            if (user == null) {
                throw new AuthenticationServiceException("ddwd");
            }

            String token = jwtTokenProvider.createToken(login, user.getRole());

            Map<String, String> response = new HashMap<>();
            response.put("login", login);
            response.put("token", token);

            return ResponseEntity.ok(response);

        } catch (AuthenticationServiceException e) {
            log.error("Error: ", e);
            throw new AuthenticationServiceException("Invalid login");
        }
    }

You can add the JWT token in localstorage and retrieve/read and pass the value with your API calls.您可以在 localstorage 中添加 JWT 令牌并检索/读取并通过 API 调用传递该值。 below is the example for setting and reading value from localstorage.下面是从 localstorage 设置和读取值的示例。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">

function createLocalstorageItem(txtJwtTokenValue) {
  sessionStorage.setItem("jwtToken", txtJwtTokenValue);
}

function readValue() {
 var jwtToken = sessionStorage.getItem("jwtToken");
console.log("jwtToken : "+jwtToken );
return jwtToken ;

}
    
function getDataFromAPiByPassingJwtTokenInHeader(){
var jwtToken=readValue();
$.ajax({
    url: 'https://url.com',
    type: 'post',
    data: {},
    headers: {
        Bearer Token: "Bearer "+jwtToken,   //key word **Bearer**  should pass before the token string
    },
    dataType: 'json',
    success: function (data) {
        console.info(data);
    }
});
}

</script>

please try this way.请尝试这种方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 登录后如何将用户重定向到基于 JWT 令牌的另一个页面? - How to redirect user to another page after login that base on JWT-token? 如何使用 JavaScript 和 HTML 使用 localStorage 存储数据? - How to store data with localStorage using JavaScript and HTML? 使用 Http 和 Secure 而不是 Javascript 中的 LocalStorage 将 Jwt 令牌存储在 Cookie 中 - Storing Jwt Token in Cookie with Http and Secure instead of LocalStorage in Javascript 在客户端 Javascript 应用程序中处理 JWT 令牌 - httpOnly Cookie 与 LocalStorage - Handling JWT Token in Client Javascript Apps - httpOnly Cookie vs LocalStorage 如何使用 NodeJS 将 jwt 令牌从控制器传递到路由器 - How to pass jwt token from controller to router using NodeJS 如何在 Angular 8 中存储像 jwt 令牌这样的数据? 是否有另一种使用本地存储或会话存储安全存储的方法? - How to store data like jwt token in Angular 8? Is there another way to store safely using localstorage or session storage? Javascript如何编写localStorage脚本 - Javascript How to write localStorage script 如何在不使用库的情况下在 javascript 中解码 jwt 令牌? - How to decode jwt token in javascript without using a library? 如何将我的 JWT 令牌存储在本地存储中? - How can I store my JWT Token in localstorage? 如何将访问令牌从PHP实现的JS脚本传递给扩展的localStorage - How to pass access token from php implemented js script to localStorage of extension
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM