All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ru.mynewtons.starter.oauth2.config.security.CustomTokenEnhancer Maven / Gradle / Ivy

package ru.mynewtons.starter.oauth2.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import ru.mynewtons.starter.oauth2.domain.UserDetails;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class CustomTokenEnhancer implements TokenEnhancer {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private TokenStore tokenStore;


    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        Map userInfo = new HashMap<>();

        UserDetails userDetails = retrieveUserDetailsFromOAuth(oAuth2Authentication);

        if (userDetails != null) {
            userInfo.put("name", userDetails.getFirstName());
            userInfo.put("surname", userDetails.getLastName());
            userInfo.put("userId", userDetails.getId());
            userInfo.put("role", userDetails.getRole());
            if (Objects.nonNull(userDetails.getUserStatus())) {
                userInfo.put("userStatus", userDetails.getUserStatus().getName());
            }

        }


        ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(userInfo);
        return oAuth2AccessToken;
    }

    private UserDetails retrieveUserDetailsFromOAuth(OAuth2Authentication oAuth2Authentication) {
        UserDetails userDetails = null;
        if (oAuth2Authentication.getPrincipal() instanceof User) {
            userDetails = (UserDetails) userDetailsService.loadUserByUsername(((User) oAuth2Authentication.getPrincipal()).getUsername());
        }

        if (oAuth2Authentication.getPrincipal() instanceof String) {
            userDetails = (UserDetails) userDetailsService.loadUserByUsername((String) oAuth2Authentication.getPrincipal());
        }

        if(oAuth2Authentication.getPrincipal() instanceof UserDetails){
            userDetails = (UserDetails) oAuth2Authentication.getPrincipal();
        }
        return userDetails;
    }


}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy