我想这样做,不需要在请求中传递 id 或用户名。 我是这样做的:
// In the controller
@DeleteMapping
public ResponseEntity<?> deleteStudent(@RequestHeader(name = "Authorization") String authHeader) {
studentService.deleteEstudiante(authHeader); // Pass the token into the service
return ResponseEntity.noContent().build();
}
// In the service
public void deleteStudent(String authHeader) {
String token = jwtService.getTokenFromAuthorizationHeader(authHeader).orElseThrow(
() -> new IllegalArgumentException("Invalid token")
);
String email = jwtService.getUsernameFromToken(token); // Get the subject
// Rest of the logic where I search the user by email in the repository and I delete it
}
但我认为这是错误的。哪个才是正确的做法?
我不能说哪种方法是正确的,因为我认为这取决于个人喜好或要求。
就我而言,我使用 JWT 过滤器,如下所示:
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain
) throws ServletException, IOException {
String token = tokenParser.resolveToken(request);
if (token != null && !token.isBlank()) {
if (blackListRepository.existsByAccessToken(token)) {
throw new TokenExpiredException();
}
Authentication authentication = tokenParser.authentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
使用此代码,我注册以下过滤器并在只能由登录用户访问的页面上执行它。过滤器验证令牌并在 Spring Security 的 SecurityContextHolder 中注册当前用户。
然后,我使用以下方法:
public User getUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
AuthDetails authDetails = null;
if (authentication.getPrincipal() instanceof AuthDetails) {
authDetails = (AuthDetails) authentication.getPrincipal();
}
if (authDetails == null || authDetails.getPhone() == null) {
throw new BasicException(ErrorCode.TOKEN_NOT_VALID);
}
return userRepository.findByPhone(authDetails.getPhone()).orElseThrow(UserNotFoundException::new);
}
我从 SecurityContextHolder 检索用户并使用它。