How to get access token just after login in successHandler in spring oauth2 security?

Viewed 844

Currently, I am working on a project where a requirement is accessToken need to be collected at spring success handler just after login. I read different blogs but couldn't found any possible solution. Here I am giving code snippet that I tried,

This is my success handler where I am trying to get accessToken. But when I am trying to cast authentication.getDetails() to OAuth2AuthenticationDetails I am getting exception.

@Component
public class AuthSuccessListener implements ApplicationListener<AuthenticationSuccessEvent> {
  
    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
     
        UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();
        System.out.println(userDetails);
        System.out.println("pass is " + userDetails.getPassword());
        System.out.println("username is " + userDetails.getUsername());

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
       //Authentication authentication = event.getAuthentication();


        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        String accessToken = details.getTokenValue();
        System.out.println(accessToken);
        
    }
}

I don't know whether this approach is valid or not. If there any other way to get accessToken just after login in successHandler or somewhere else, then please help to solve this issue.

1 Answers

At least I found a solution to get token at succeshandler just after login. As I haven't got relevant solution in short, that's why I am posting this answer. I solved the issue like this.

    @Component
    public class AuthSuccessListener implements ApplicationListener<AuthenticationSuccessEvent> {
    
        private final TokenStore tokenStore;
    
        public AuthSuccessListener(TokenStore tokenStore) {
            this.tokenStore = tokenStore;
        }
    
        @Override
        public void onApplicationEvent(AuthenticationSuccessEvent event) {
            UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();
            String accessToken = null;
            List<OAuth2AccessToken> tokens = (List<OAuth2AccessToken>) tokenStore.findTokensByClientIdAndUserName("your Client Id", userDetails.getUsername());
            if (tokens.size() > 0) {
                accessToken = tokens.get(0).getValue();
            }
        }
    }

Here you can see I used TokenStore to reteive token by using clientId and username with method tokenStore.findTokensByClientIdAndUserName("your Client Id", userDetails.getUsername()); That's it.

Related