gpt4 book ai didi

angular - 无法在 Java Spring Boot/Angular 应用程序中获取 cookie

转载 作者:行者123 更新时间:2023-12-05 03:43:42 25 4
gpt4 key购买 nike

我正在开发一个 Angular11 前端应用程序以及一个 Java Spring 启动后端。

上下文

我正在尝试使用 JWT 创建带有 cookie 的身份验证。为此,我受到了启发

我的端点 /authenticate 返回一个 jwt 访问 token 并在 cookie 中设置一个 jwt 刷新 token (httpOnly)。
我的端点 /refreshtoken 从 cookie 中获取刷新 token 并在生成新的 jwt 访问 token 和新的 jwt 刷新 token 之前对其进行验证。
这是我的 AuthenticationController

的代码
    @RestController
@AllArgsConstructor
@CrossOrigin(origins = "http://localhost:4200", allowCredentials = "true")
public class AuthenticationController {

private final AuthenticationManager authenticationManager;
private final JwtTokenUtil jwtTokenUtil;
private final UserDetailsServiceImpl userDetailsService;
private final static String REFRESH_TOKEN_COOKIE = "resfreshtoken";

@PostMapping(value = "/authenticate")
public ResponseEntity<JwtAuthenticationResponse> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, HttpServletResponse response) throws Exception {
try {
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword()));
}
catch (DisabledException e) {
throw new Exception("USER_DISABLED", e);
}
catch (BadCredentialsException e) {
throw new Exception("INVALID_CREDENTIALS", e);
}
final UserDetails userDetails = this.userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
final String token = this.jwtTokenUtil.generateToken(userDetails.getUsername());
final String refreshToken = this.jwtTokenUtil.generateRefreshToken(new HashMap<>(), userDetails.getUsername());

Cookie cookie = new Cookie(REFRESH_TOKEN_COOKIE, refreshToken);
cookie.setHttpOnly(true);
// cookie.setDomain("localhost");
// cookie.setPath("/");
response.addCookie(cookie);

return ResponseEntity.ok(new JwtAuthenticationResponse(token));
}

@GetMapping(value = "/refreshtoken")
public ResponseEntity<?> refreshToken(@CookieValue(value = REFRESH_TOKEN_COOKIE, required = false) String refreshToken, HttpServletRequest request, HttpServletResponse response) {
Cookie[] cookies = request.getCookies(); // ALWAYS returns null
log.debug("refreshToken {}", refreshToken); // ALWAYS null
try {
Claims claims = this.jwtTokenUtil.getAllClaimsFromToken(refreshToken);
final String username = claims.get("sub").toString();
final String newAccessToken = this.jwtTokenUtil.generateToken(username);
final String newRefreshToken = this.jwtTokenUtil.generateRefreshToken(claims, username);
CookieUtil.writeCookie(response, REFRESH_TOKEN_COOKIE, newRefreshToken);

return ResponseEntity.ok(new JwtAuthenticationResponse(newAccessToken));
}
catch (SignatureException | MalformedJwtException | UnsupportedJwtException | IllegalArgumentException ex) {
throw new BadCredentialsException("INVALID_CREDENTIALS", ex);
}
catch (ExpiredJwtException e) {
// user should re-login
}

return new ResponseEntity<>("Something went wrong", HttpStatus.BAD_REQUEST);
}
}

在 Angular 前端,这是我添加到/refreshtoken Http 请求的选项 (withCredentials=true)

refreshToken(): Observable<AuthenticationResponse> {
return this.http.get<AuthenticationResponse>(this.apiUrl + 'refreshtoken', { withCredentials: true }).pipe(
tap(response => LocalStorageUtils.save(LocalStorageKey.JWT_ACCESS_TOKEN_KEY, response.jwtAccessToken))
);
}

我的问题

如果我尝试到达我的端点 /authenticate 然后 /refreshtoken 来自 postman ,一切正常,我可以看到 cookie
如果我从我的前端调用 /authenticate,我可以在标题为 SET-COOKIE 的响应中看到 cookie(在 cookies 选项卡中) enter image description here但是,如果我从我的前端调用 /refreshtoken,我就无法使用 request.getCookies()@CookieValue() 获取 cookie后端,它总是返回 null !
似乎该 cookie 在前端很受欢迎,但没有设置(我在 application 选项卡 -> Chrome 上的 cookie 中看不到它)。
因此它不会与/refreshtoken 请求一起发送

如果有人可以提供帮助或知道出了什么问题,我将不胜感激!如果需要,我可以提供有关我的代码的更多详细信息。

最佳答案

您需要将 withCredentials: true 添加到您的 httpOptions 并在每个请求中将其与 HttpClient 一起传递。您还可以使用 HttpClient 和拦截器对其进行全局配置。

关于angular - 无法在 Java Spring Boot/Angular 应用程序中获取 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66660840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com