Shahid Neermunda
Shahid Neermunda

Reputation: 1357

Add new field in Spring Boot Oauth2 response

I am crated a Spring Boot Oauth2 Authentication and worked fine. I need to add usertype field with Oauth2 response.

My Code given below.

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

static final String CLIEN_ID = "client";
//static final String CLIENT_SECRET = "devglan";
static final String CLIENT_SECRET = "$2a$04$e/c1/RfsWuTh/vj/BfG";
static final String GRANT_TYPE = "password";
static final String AUTHORIZATION_CODE = "authorization_code";
static final String REFRESH_TOKEN = "refresh_token";
static final String IMPLICIT = "implicit";
static final String SCOPE_READ = "read";
static final String SCOPE_WRITE = "write";
static final String TRUST = "trust";
static final int ACCESS_TOKEN_VALIDITY_SECONDS = 50*60*60;
static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 66*60*60;

@Autowired
private TokenStore tokenStore;

@Autowired
private AuthenticationManager authenticationManager;

@Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {

    configurer
            .inMemory()
            .withClient(CLIEN_ID)
            .secret(CLIENT_SECRET)
            .authorizedGrantTypes(GRANT_TYPE, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT )
            .scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
            .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS).
            refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.tokenStore(tokenStore)
            .authenticationManager(authenticationManager);
}
 }

The Response after authentication is given below

{"access_token":"b3336423-ed9d-4d91-a308-2a5d16dbc037","token_type":"bearer","refresh_token":"135f6f95-8f5b-404a-83fc-11e12bf772be","expires_in":179999,"scope":"read write trust"}

I need to add usertype field to above response.

Upvotes: 2

Views: 1017

Answers (2)

Tanbir Ahmed
Tanbir Ahmed

Reputation: 320

Although there is nothing wrong with the previous approach, you can also use the UserDetails to save an additional call to the database in the CustomTokenConverter class.

@Component
public class CustomTokenConverter extends JwtAccessTokenConverter {

     @Override
     public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

         final Map<String, Object> additionalInfo = new HashMap<>();
         CustomUserDetail principal = (CustomUserDetail) authentication.getPrincipal();

         additionalInfo.put("usertype", principal.getUserType());

         ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

         return super.enhance(accessToken, authentication);
     }
}

In this case, you would need to add the userType property in the CustomUserDetail class

public class CustomUserDetail implements UserDetails {

    private String userType;
    
    // ....

    public CustomUserDetails(User user) {
         this.userType = user.getUserType();
    }
  
    public String getUserType(){
         return this.userType;
    }
    // ....
    
}

Upvotes: 0

Shahid Neermunda
Shahid Neermunda

Reputation: 1357

I got solution for this Create CustomTokenConverter class

@Component
public class CustomTokenConverter extends JwtAccessTokenConverter {

    @Autowired
    private UserRepository userRepository;

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

        final Map<String, Object> additionalInfo = new HashMap<>();
        User user = userRepository.findByUsername(authentication.getName());

        additionalInfo.put("usertype", user.getTypeOfUser());

        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

        return super.enhance(accessToken, authentication);
    }

}

and Update AuthorizationServerConfig class

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .tokenEnhancer(customTokenEnhancer())
                .authenticationManager(authenticationManager);
    }
    

    @Bean
    public CustomTokenConverter customTokenEnhancer() {
        return new CustomTokenConverter();
    }

Now I got the response like this

{"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSIsInRydXN0Il0sInVzZXJ0eXBlIjoiQWRtaW4iLCJleHAiOjE1NzcyODA3ODYsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iXSwianRpIjoiZDk4MTkxOWYtZDMzOC00YTE2LTk4NTEtYWFjODUzZWYyOGE4IiwiY2xpZW50X2lkIjoiZGV2Z2xhbi1jbGllbnQifQ.BuuVK6HFajOM9vryciwBi6-aMSMOrV5E0YiPyPmZ0Uw","token_type":"bearer","refresh_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSIsInRydXN0Il0sImF0aSI6ImQ5ODE5MTlmLWQzMzgtNGExNi05ODUxLWFhYzg1M2VmMjhhOCIsInVzZXJ0eXBlIjoiQWRtaW4iLCJleHAiOjE1NzczMzgzODYsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iXSwianRpIjoiZGNjYTEyZDUtNzY1Ny00N2I5LThkYmMtNTkzOWQzZDk3MWYzIiwiY2xpZW50X2lkIjoiZGV2Z2xhbi1jbGllbnQifQ.L_vguBCDOeAGNlq-L-OiPO6TW2gRXNBv562JnyR3uSE","expires_in":179999,"scope":"read write trust","usertype":"Admin","jti":"d981919f-d338-4a16-9851-aac853ef28a8"}

Thank You

Upvotes: 1

Related Questions