Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

java - Spring security: Failed authentication with more details

I'm trying to get the exact motive for a failed autentication (i.e wrong password, user doesn't exist, and so on) problem is, no matter how I try do simulate this actions I always get "Full authentication is required to access this resource", how can I get a more detailed exception ? TKS in advance !

Here's my code:

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

    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can analyze the specific exception that was thrown from the AuthenticationException superclass and act accordingly:

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

    }
}

You can find a better list of AuthenticationException known subclasses here: https://docs.spring.io/spring-security/site/docs/4.2.19.RELEASE/apidocs/org/springframework/security/core/AuthenticationException.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...