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

huangapple go评论74阅读模式
英文:

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

问题

我正在为一个在线咖啡茶商店编写一个Rest MVC应用程序。使用以下技术:Spring-BootHibernatePostgreSQLGradleThymeleafHTMLCSS。整个后端已经准备好,接下来需要制作前端。目前我正在制作一个授权页面。页面本身已经使用HTMLCSS准备好了,现在需要编写授权逻辑本身。为此,我需要在javascript中编写脚本,以便我的jwt token存储在localStorage中。关键是我不知道如何实现这一点,如何通过javascriptlocalStorage中通过header传递我的token

重要提示:javascript必须是纯净的,不能使用框架(angularnode等)。我应该如何做?

P.S. 再次强调,整个后端已经准备就绪。Rest授权方法可用(也就是说,我输入我的loginpassword - 就会得到一个jwt token)。

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");
    }
}

图片已移除。

英文:

I am writing a Rest MVC application for an online coffee and tea store. The following technologies are used: Spring-Boot, Hibernate, PostgreSQL, Gradle, Thymeleaf, HTML, CSS. 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. To do this, I need to write a script in javascript so that my jwt token is stored in 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.

Important: javascript must be clean, without using frameworks (angular, node ...). How should I do it?

P.S. Again, the whole backand is ready. Rest-authorization method works (that is, I enter my login and password - I get a jwt token).

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

Java - authorization method

 public ResponseEntity&lt;Map&lt;String, String&gt;&gt; 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(&quot;ddwd&quot;);
            }

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

            Map&lt;String, String&gt; response = new HashMap&lt;&gt;();
            response.put(&quot;login&quot;, login);
            response.put(&quot;token&quot;, token);

            return ResponseEntity.ok(response);

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

答案1

得分: 1

你可以将JWT令牌存储在本地存储中,然后在API调用时检索/读取并传递该值。以下是设置和从本地存储中读取值的示例:

<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: {
        "Authorization": "Bearer "+jwtToken,   //关键词 **Bearer** 应该在令牌字符串之前传递
    },
    dataType: 'json',
    success: function (data) {
        console.info(data);
    }
});
}

</script>
请尝试这种方式。
英文:

You can add the JWT token in localstorage and retrieve/read and pass the value with your API calls. below is the example for setting and reading value from localstorage.

&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;

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

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

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

&lt;/script&gt;

please try this way.

huangapple
  • 本文由 发表于 2020年9月11日 00:41:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63834132.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定