过滤器:
@Autowired
UnauthenticatedRequestHandler unauthenticatedRequestHandler;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try{
if (!isValid) throw new BadCredentialsException("exception.jwt.inValid");
if (!accessTokenDTO.isValid()) throw new BadCredentialsException("exception.token.inValid");
if (!user.isEmailVerified()) throw new DisabledException("exception.user.notVerified");
filterChain.doFilter(request, response);
}
catch (AuthenticationException ex){
unauthenticatedRequestHandler.commence(request,response,ex);
}
处理程序:
@Component
public class UnauthenticatedRequestHandler implements
AuthenticationEntryPoint {
final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private MessageSource messageSource;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
log.error(authException.toString());
String message = messageSource.getMessage(authException.getMessage(),null,null, Locale.getDefault());
if(message == null) message = authException.getMessage();
ResponseDTO<Object> res = ResponseDTO.builder()
.status(false)
.message(message)
.build();
String jsonString = new ObjectMapper().writeValueAsString(res);
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getOutputStream().println(jsonString);
}
在安全配置中注册AuthenticationEntryPoint。
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthenticatedHandler).and()}