【问题标题】:Spring OAuth/JWT get extra information from access tokenSpring OAuth/JWT 从访问令牌中获取额外信息
【发布时间】:2016-05-10 00:41:17
【问题描述】:

我制作了一个简单的应用程序,它使用带有 oauth/jwt 提供程序的 spring 安全性。 我通过自定义 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:注入良好,但不包含其他信息或 accesstoken 对象(它仅包含原始 jwt 令牌字符串)。
  • User 是对 OAuth2Authentication 的引用
  • OAuth2AccessToken:是没有任何信息的aop代理,事实上对象A和B都是空的。

一些额外的信息:

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

【问题讨论】:

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


    【解决方案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;
    }
    

    【讨论】:

    • 嗨,卡尔,我正在尝试做同样的事情。你在哪里挂钩你的“myUserConverter”?
    • public void configure(AuthorizationServerEndpointsConfigurer endpoints) { endpoints .authenticationManager(authenticationManager) .tokenStore(new JwtTokenStore(converter)) .accessTokenConverter(converter) .userDetailsS​​ervice(userDetails); }
    猜你喜欢
    • 2015-06-23
    • 2018-03-06
    • 2021-02-15
    • 2023-03-27
    • 1970-01-01
    • 2013-11-05
    • 2018-01-13
    • 2018-02-17
    • 1970-01-01
    相关资源
    最近更新 更多