Spring Security :失败的身份验证和更多细节

bnl4lu3b  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(262)

我试图获得失败的身份验证的确切动机(即错误的密码,用户不存在,等等)问题是,无论我如何尝试模拟此操作,我总是得到“需要完全身份验证才能访问此资源”,如何才能得到更详细的异常?提前准备!
这是我的密码:

@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);

    }
}
0h4hbjxa

0h4hbjxa1#

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

相关问题