我正在尝试创建弹簧安全应用程序
我像这样实现了SecurityConfig
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.formLogin().disable()
.httpBasic().disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.anyRequest()
.authenticated();
// Add our custom JWT security filter
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
我的 JwtAuthenticationEntryPoint 来处理异常:
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);
@Override
public void commence(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
AuthenticationException e) throws IOException, ServletException {
logger.error("Responding with unauthorized error. Message - {}", e.getMessage());
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
}
}
我还实现了 UserDetail 服务
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
@Transactional
public UserDetails loadUserByUsername(String usernameOrEmail)
throws UsernameNotFoundException {
User user = userRepository.findByUsernameOrEmail(usernameOrEmail, usernameOrEmail)
.orElseThrow(() ->
new UsernameNotFoundException
("User not found with username or email : " + usernameOrEmail)
);
return UserPrincipal.create(user);
}}
在添加 ControllerAdvice 之前它工作正常
@ControllerAdvice
public class ExceptionControllerAdvice {
/**** 500 Entity */
@ExceptionHandler(value = Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public final ErrorDetail handleAllExceptions(Exception ex) {
LOGGER.error("An unexpected error occurred", ex);
ErrorDetail problem = new ErrorDetail("Internal Error",
"An unexpected error has occurred");
problem.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
return problem;
}
}
现在 spring 正在尝试处理控制器建议中的异常。结果,我无法正确处理该错误。如果我注释掉控制器建议逻辑,那么 AuthenticationEntryPoint 将被处理身份验证错误。
如何让 AuthenticationEntryPoint 和 @ControllerAdvice 协同工作?
嘿,这个问题你解决了吗?