1
votes

I'm trying the catch and customize Authentication exception thrown in Customized Authentication Filter but once the exception is thrown it always goes to the provider manager class and sends default spring API error response.

  1. WebSecurity Config class
@Configuration

public static class RestAPISecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    AuthenticationEntry authenticationEntryPoint;

    @Autowired
    BasicAuthenticationProvider customAuthProvider;

    @Autowired
    AuthenticationFailureHandler accessDeniedHandler;

    private final RequestMatcher PROTECTED_URLS = new OrRequestMatcher(
            new AntPathRequestMatcher(API_PATH_IDENTIFIER));

    @Value("${username}")
    private String userName;

    @Value("${password}")
    private String password;

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(customAuthProvider);
        auth.inMemoryAuthentication().withUser("abcd").password(passwordEncoder().encode("sample@123"))
                .roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().authorizeRequests().antMatchers("/api")
                .authenticated().and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(SECURITY_EXCLUDED_PATHS);
    }

}

AuthenticationProvider class:


@Component
public class BasicAuthenticationProvider implements AuthenticationProvider {
    
    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;
    
    @Override
    public Authentication authenticate(Authentication auth) throws UserAuthenticationException
      {
        String username = auth.getName();
        String password = auth.getCredentials()
            .toString();
        AuthenticationException exception = null;
        
        
        try {

        if ("abcd".equals(username) && "Sample@123".equals(password)) {
            return new UsernamePasswordAuthenticationToken
              (username, password, Collections.emptyList());
        } else {
            
           throw new BadCredentialsException("invalid user");
           
        }
        
        
    }catch(AuthenticationException e)
        {
         exception = e;

         throw exception;
         
        }
      }

    @Override
    public boolean supports(Class<?> auth) {
        return auth.equals(UsernamePasswordAuthenticationToken.class);
    }

    
}

AuthenticationEntryPOint class:


/**
 *
 * Authentication entry point to handle security exceptions
 *
 */
@Component
public class AuthenticationEntry implements AuthenticationEntryPoint{
    
    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;
    
    /**
     *This handles security exceptions and redirects it to exception handler
     */
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws UserAuthenticationException {
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        resolver.resolveException(httpServletRequest, httpServletResponse, null, new UserAuthenticationException("Not Authorized"));
    }

}
1
You shouldn't. What is it you want to customize?M. Deinum
The current implementation sends the following error response:shantih.antony
I want to customize the above response to a user-friendly messageshantih.antony
THen throw an exception with a proper message or provide a better message to providing a proper mapping from this error to a message through the I18N infrastructure.M. Deinum
yes, I can modify the error message but I have a default error response for all the unauthorized requests in my application. I want to send something like below, {"status": "failure", "message": "You are unauthorized to access this API")shantih.antony

1 Answers

0
votes

you can do the exception in the filterChain