1

I am using Spring-cloud-oauth2 to create an authorisation server. It is based on both client credentials and Username and password. My problem is that I am not able to customise the error response for bad credentials when typing incorrect username-password. I controlled the error response for wrong client credentials by implementing the AuthenticationEntryPoint interface. Similar to that I tied to handle Bad credential response, using AuthenticationFailureHandler by following Baeldung tutorial. But it seems like failure handler is not getting registered and so onAuthenticationFailure method is never getting executed. What I am trying to achieve is a solution for exactly this question.

Following is a part of the relevant code:

@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    Logger logger=LoggerFactory.getLogger(CustomAuthenticationFailureHandler.class);

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

        httpServletResponse.setStatus(HttpStatus.BAD_REQUEST.value());

        Map<String, Object> data = new HashMap<>();
        data.put("timestamp", new Date());
        data.put("exception", e.getMessage());

        httpServletResponse.getOutputStream().println(objectMapper.writeValueAsString(data));

    }
}
// CustomAuthenticationFailureHandler.Class

Following is my WebSecurityConfigurerAdapter:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService customUserDetailsService;

    @Autowired
    private AuthenticationProvider customAuthenticationProvider;

    @Autowired
    AuthenticationEntryPoint customAuthenticationEntryPoint;

    @Autowired
    private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;



    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthenticationProvider);
        // auth.userDetailsService(customUserDetailsService).passwordEncoder(encoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/jwks-json")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .failureHandler(customAuthenticationFailureHandler)
                .and()
                .httpBasic().
                and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.NEVER);

        http.exceptionHandling().authenticationEntryPoint(customAuthenticationEntryPoint);

        //http.addFilterAfter(customExceptionTranslation(),ExceptionTranslationFilter.class);


    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder encoder(){



        PasswordEncoder defaultEncoder = new BCryptPasswordEncoder();

        Map<String, PasswordEncoder> encoders = new HashMap<>();
        encoders.put("noop", NoOpPasswordEncoder.getInstance());
        encoders.put("bcrypt", new BCryptPasswordEncoder());

        DelegatingPasswordEncoder passworEncoder = new DelegatingPasswordEncoder(
                "bcrypt", encoders);

        passworEncoder.setDefaultPasswordEncoderForMatches(defaultEncoder);

        return passworEncoder;
    }

Please tell me where I am doing wrong. Thanks in advance

ng-security-custom-authentication-failure-handler

Community
  • 1
  • 1
sebin vincent
  • 330
  • 3
  • 12
  • Check if the solution works for you https://stackoverflow.com/questions/62368896/custom-error-objects-for-spring-rest-api-and-swagger-ui/62370012#62370012 – Suraj Jun 14 '20 at 10:36
  • Sorry this seems like not working @S – sebin vincent Jun 14 '20 at 13:18
  • have you tried removing the ` .failureHandler(customAuthenticationFailureHandler)` from configure and then running the solution mentioned in the previous comment? – Suraj Jun 14 '20 at 13:51
  • I tried it now. But still, I couldn't make it. Did you know about some filter which actually gives this original response? – sebin vincent Jun 14 '20 at 14:26

1 Answers1

1

You can try to create a CustomOauthException which extends OAuth2Exception as mentioned in this link medium blog for customising oauth response.Then you can customize the response given by the CustomOauthException using a custom JsonSerializer.

This is an another approach to achieve the same use case.Though I don't know why onAuthenticationFailure isn't getting executed in the given code.

Hope this helps.

sachin
  • 1,220
  • 1
  • 14
  • 24