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?
PS 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");
}
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.