Spring OAuth / JWT从访问令牌

时间:2016-02-01 14:09:42

标签: spring oauth spring-security jwt spring-security-oauth2

我创建了一个使用spring安全性和oauth / jwt提供程序的简单应用程序。 我通过自定义JwtAccessTokenConverter在jwt标记中添加了额外的信息,它运行良好。

我的问题是如何在我的Rest Controller中获取这些额外的信息。

这是我的测试:

@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();
...
}

结果是:

  • OAuth2Authentication:注入井但不包含其他信息或者accessstoken对象(它只包含原始的jwt令牌字符串)。
  • 用户是对OAuth2Authentication的引用
  • OAuth2AccessToken:是没有任何信息的aop代理,对象A和B都是null。

一些额外信息:

  • 我通过调试检查了ResourceService是否使用了我的JwtAccessTokenConverter并从输入中的访问令牌字符串中提取了附加信息列表。

1 个答案:

答案 0 :(得分:1)

我找到了一个可能的解决方案。

我在JwtAccessTokenConverter中设置了DefaultAccessTokenConverter,我设置了自定义UserTokenConverter。

所以.. JwtAccessTokenConverter只管理访问令牌的jwt方面(令牌验证和提取),新的DefaultAccessTokenConverter管理访问令牌转换的oauth方面,包括使用我的自定义UserTokenConverter创建带有从jwt令牌中提取的自定义信息的Pricipal。

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;
}