英文:
How to pass JWT-TOKEN to localStorage using JavaScript (script for html)?
问题
我正在为一个在线咖啡茶商店编写一个Rest
MVC
应用程序。使用以下技术:Spring-Boot
,Hibernate
,PostgreSQL
,Gradle
,Thymeleaf
,HTML
,CSS
。整个后端已经准备好,接下来需要制作前端。目前我正在制作一个授权页面。页面本身已经使用HTML
和CSS
准备好了,现在需要编写授权逻辑本身。为此,我需要在javascript
中编写脚本,以便我的jwt token
存储在localStorage
中。关键是我不知道如何实现这一点,如何通过javascript
在localStorage
中通过header传递我的token
。
重要提示:javascript
必须是纯净的,不能使用框架(angular
,node
等)。我应该如何做?
P.S. 再次强调,整个后端已经准备就绪。Rest
授权方法可用(也就是说,我输入我的login
和password
- 就会得到一个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
).
Java - authorization method
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");
}
}
答案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.
<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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论