java - Spring security:身份验证失败,提供更多详细信息
问题描述
我正在尝试获取身份验证失败的确切动机(即密码错误,用户不存在等)问题是,无论我如何尝试模拟此操作,我总是得到“需要完全身份验证才能访问这个资源”,我怎样才能得到更详细的异常?提前TKS!
这是我的代码:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Autowired
UnauthorizedCustomResponse unauthorizedCustomResponse;
@Autowired
AccessDeniedCustomResponse accessDeniedCustomResponse;
@Autowired
CryptographyService cryptographyService;
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(userService)
.passwordEncoder(cryptographyService.getCryptography());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/auth/signin", "/api/public/**", "/api/private/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedCustomResponse)
.accessDeniedHandler(accessDeniedCustomResponse)
.and()
.httpBasic();
}
}
@Component
public class AccessDeniedCustomResponse implements AccessDeniedHandler {
private final Logger logger = LogManager.getLogger(this.getClass());
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception)
throws IOException, ServletException {
logger.error("Usuário não autenticado: {}", exception.getMessage());
CustomException customException = new CustomException(CustomExceptionMessage.CUSTOM_EXCEPTION_NOT_MAPPED, exception);
customException.flush(response);
}
}
@Component
public class UnauthorizedCustomResponse implements AuthenticationEntryPoint {
private final Logger logger = LogManager.getLogger(this.getClass());
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
logger.error("Acesso não autorizado: {}", exception.getMessage());
CustomException customException = new CustomException(CustomExceptionMessage.ACCESS_DENIED, exception);
customException.flush(response);
}
}
解决方案
您可以分析从 AuthenticationException 超类引发的特定异常并采取相应措施:
@Component
public class UnauthorizedCustomResponse implements AuthenticationEntryPoint {
private final Logger logger = LogManager.getLogger(this.getClass());
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
if(exception.getClass().isAssignableFrom(UsernameNotFound.class)) {
//Username not found
}
else if (exception.getClass().isAssignableFrom(BadCredentials.class)) {
//Bad credentials error
}
else if (exception.getClass().isAssignableFrom(AccountStatusException.class)) {
//Accound status exception
}
logger.error("Acesso não autorizado: {}", exception.getMessage());
CustomException customException = new CustomException(CustomExceptionMessage.ACCESS_DENIED, exception);
customException.flush(response);
}
}
您可以在此处找到更好的 AuthenticationException 已知子类列表:https ://docs.spring.io/spring-security/site/docs/4.2.19.RELEASE/apidocs/org/springframework/security/core/AuthenticationException.html
推荐阅读
- .net - docker 容器的 CPU 利用率低
- python - 不明白为什么会出现错误“NameError: name 'raw_input' is not defined”
- python-3.x - 如何比较python中多个列表的相同索引处的变量
- iis - 在iis中重定向到www?
- python - 为什么我的正则表达式没有返回任何匹配项?
- python - 建议在 python 3.6 脚本和 python 2.7 脚本之间传递数据
- symfony - Symfony JMS Serializer - 上传文件的端点
- java - 请求 HttpResponse 时 Android 应用程序崩溃
- python - oracle datetime 字段 spark 读取失败并出现精度错误
- python - 课堂内情节刷新