当 jwt 令牌无效或过期时,为什么不调用此开始方法?当令牌为空时会调用它。奇怪的是,在调试时我发现当令牌无效或过期时,会调用 BearerTokenAuthenticationEntryPoint.commence() 方法。这个类是标准java库的一部分,并且是最终的,所以不能扩展。但它实现了与我实现相同的接口 - AuthenticationEntryPoint,但我的开始方法仍然没有被调用。仅当令牌为空时才会调用它。
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
public CustomAuthenticationEntryPoint() {
}
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException authenticationException) throws IOException {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
HttpStatus status = HttpStatus.UNAUTHORIZED;
final Map<String, Object> body = new HashMap<>();
body.put("status", status.name());
body.put("statusCode", status.value());
body.put("message", "You need to login first in order to perform this action");
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), body);
}
}
Run Code Online (Sandbox Code Playgroud)
我这样使用它:
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authorize) -> …Run Code Online (Sandbox Code Playgroud)