Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

oauth2 spring-security success and failure handler

I am using Spring Security with OAuth2. It's working fine except login success and failure handlers.

Like in spring web security OAuth2 does not have clearly defined success and failure handlers hooks to update DB and set response accordingly.

What filter do I need to extend and what should its position be in the Spring Security filter chain?

like image 679
user3696428 Avatar asked Jun 01 '14 09:06

user3696428


2 Answers

Specify successHandler and failureHandler for oauth2login method:

@Configuration
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${successUrl}")
    private String successUrl;
    @Value("${failureUrl}")
    private String failureUrl;

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

        http
            .oauth2Login()
                .successHandler(successHandler())
                .failureHandler(failureHandler());
    }

    @Bean
    SimpleUrlAuthenticationSuccessHandler successHandler() {
        return new SimpleUrlAuthenticationSuccessHandler(successUrl);
    }
    
    @Bean
    SimpleUrlAuthenticationFailureHandler failureHandler() {
        return new SimpleUrlAuthenticationFailureHandler(failureUrl);
    }
}

Tested for Spring Security 5.0.6

like image 74
MariuszS Avatar answered Oct 26 '22 09:10

MariuszS


I personally use

@Component
public class MyAuthenticationSuccessListener implements ApplicationListener<AuthenticationSuccessEvent> {

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        System.out.println("Authenticated");
    }

}

Additional informations in response can be set by CustomTokenEnhancer

like image 25
dagi12 Avatar answered Oct 26 '22 09:10

dagi12