Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring OAuth/JWT get extra information from access token

I made a simple application that use spring security with oauth/jwt provider. I added extra information in jwt token by custom JwtAccessTokenConverter and it works well.

My issue is how gets these extra informations in my Rest Controller.

This is my test:

@RequestMapping(value = "/test", produces = { "application/json" },method = RequestMethod.GET) 
public String testMethod(OAuth2Authentication authentication,
        OAuth2AccessToken token,
Principal user){
.....
Object a=token.getAdditionalInformation();
Object b=token.getValue();
...
}

The results are:

  • OAuth2Authentication: well inject but don't contain additional informations or accesstoken object (it contains only the original jwt token string).
  • User is a reference to OAuth2Authentication
  • OAuth2AccessToken: is aop proxy without any information infact object A and B are null.

Some extra info:

  • I checked,by debug, that ResourceService use my JwtAccessTokenConverter and extract the list of additional information from the access token string in input.
like image 732
Alessandro Avatar asked Feb 01 '16 14:02

Alessandro


1 Answers

I found a possible solution.

I set in my JwtAccessTokenConverter a DefaultAccessTokenConverter where i set my custom UserTokenConverter.

So.. The JwtAccessTokenConverter manage only the jwt aspect of access token (token verification and extraction), the new DefaultAccessTokenConverter manages the oauth aspect of access token convertion including the use of my custom UserTokenConverter to create the Pricipal with custom informations extracted from jwt token.

public class myUserConverter extends DefaultUserAuthenticationConverter {
 public Authentication extractAuthentication(Map<String, ?> map) {
     if (map.containsKey(USERNAME)) {
        // Object principal = map.get(USERNAME);
        Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
        UserDto utente = new UserDto();
        utente.setUsername(map.get(USERNAME).toString());
        utente.setUfficio(map.get("ufficio").toString());
        utente.setExtraInfo(map.get("Informazione1").toString());
        utente.setNome(map.get("nome").toString());
        utente.setCognome(map.get("cognome").toString());
        utente.setRuolo(map.get("ruolo").toString());

        return new UsernamePasswordAuthenticationToken(utente, "N/A", authorities);
    }
    return null;
}
like image 103
Alessandro Avatar answered Oct 18 '22 20:10

Alessandro