2

I set an additional information by using OAuth2AccessToken enhance. I can see the additional information in the token but how can I get that list in my services class?

public final class CustomTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(
            OAuth2AccessToken accessToken,
            OAuth2Authentication authentication) {
        Map<String, Object> additionalInfo = new HashMap<>();

        List<String> companies = new ArrayList<>();
        companies.add("Company 1");
        companies.add("Company 2");
        companies.add("Company 3");

        additionalInfo.put("companies", companies);

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

I tried to get authentication from security context and cascade it to Oauth2Authentication but that object doesn't have additional information list.

SecurityContext securityContext = SecurityContextHolder.getContext();
OAuth2Authentication oauth = (OAuth2Authentication)securityContext.getAuthentication();
pvpkiran
  • 25,582
  • 8
  • 87
  • 134
Eniss
  • 975
  • 2
  • 20
  • 40
  • Possible duplicate of [can I include user information while issuing an access token?](https://stackoverflow.com/questions/28492116/can-i-include-user-information-while-issuing-an-access-token) – dur Apr 18 '18 at 13:26

1 Answers1

0

This is how I fetched additional info named department:

@PreAuthorize("hasAuthority('ROLE_ACCOUNTS') and #oauth2.hasScope('READ')")
@GetMapping()
public List<Account> getAll(OAuth2Authentication principal) {

    OAuth2AuthenticationDetails auth2AuthenticationDetails = (OAuth2AuthenticationDetails) principal.getDetails();
    Map<String, Object> details = tokenStore.readAccessToken(auth2AuthenticationDetails.getTokenValue()).getAdditionalInformation();
    String department= (String) details.get("department");
    return accountService.getAllAccounts(department);
}
dur
  • 15,689
  • 25
  • 79
  • 125
Udara S.S Liyanage
  • 6,189
  • 9
  • 33
  • 34