Issue
I'm successfully creating a JWT token. And the login works fine. But the JWT Token is not sotred in cookies. At least in my browser, from Postman it seems to work. Every time I send a POST request to the signin route I get a Header with name Cookie and this Value:
JSESSIONID=censored authToken=censored
The authToken does match with my newest generated JWT Token. But browser side there is no cookie.
This is my spring boot service:
@Override
public String login(LoginDTO loginDto, HttpServletRequest request, HttpServletResponse response) {
Optional<UserEntity> userOptional = userRepository.findByEmail(loginDto.getEmail());
if (userOptional.isEmpty()) {
throw new InvalidRequestException(messageSource.getMessage("EMAIL_OR_PASSWORD_INVALID", null, myLocaleResolver.resolveLocale(request)));
}
try {
UserEntity user = userOptional.get();
if (!user.isEnabled()) {
throw new InvalidRequestException(messageSource.getMessage("EMAIL_NOT_VERIFIED", null, myLocaleResolver.resolveLocale(request)));
}
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginDto.getEmail(),
loginDto.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = jwtGenerator.generateToken(authentication.getName(), "login");
Cookie authTokenCookie = new Cookie("authToken", token);
authTokenCookie.setHttpOnly(true);
authTokenCookie.setPath("/");
authTokenCookie.setMaxAge(60 * 60 * 24 * 30); // 30 days
System.out.println("authTokenCookie Name: " + authTokenCookie.getName());
System.out.println("authTokenCookie Value: " + authTokenCookie.getValue());
response.addCookie(authTokenCookie);
return token;
} catch (BadCredentialsException e) {
throw new InvalidRequestException(messageSource.getMessage("EMAIL_OR_PASSWORD_INVALID", null, myLocaleResolver.resolveLocale(request)));
}
}
My angular code:
registerUser(form: NgForm) {
if (this.email.valid && this.password.valid) {
const data = {
email: this.email.value,
password: this.password.value
};
this.isLoading = true;
this.http.post('http://localhost:8080/signin', data, {
headers: {'Accept-Language': this.language},
responseType: 'json'
}).subscribe(
(response: any) => {
setTimeout(() => {
this.toastr.success(response.message);
this.router.navigate(['/']);
this.isLoading = false;
}, 2500);
},
(error: any) => {
setTimeout(() => {
this.toastr.error(error.error);
this.isLoading = false;
}, 1000);
}
)
}
}
My server log
authTokenCookie Name: authToken authTokenCookie Name: censored
Solution
Solution: If you work with CORS you need to enable allowCredentials. Either with the annotation
@CrossOrigin(origins = "http://MY_IP_ADDRESS", allowCredentials = "true")
or in the WebMvcConfig
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(org.springframework.web.servlet.config.annotation.CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:4200")
.allowedMethods("*")
.allowCredentials(true);
}
}
You'll also have to enable withCredentials in the frontend. This solution is for angular:
...
this.http.post('http://localhost:8080/...', data, {
headers: {'Accept-Language': this.language},
withCredentials: true,
responseType: 'json'
}
...
Answered By - Zut4too
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.