Spring security:身份验证失败,详细信息

时间:2021-01-07 14:03:43

标签: java spring 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);

    }
}

1 个答案:

答案 0 :(得分:0)

您可以分析从 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