【问题标题】:Jwt add claims to token in Spring bootJwt 在 Spring Boot 中添加对令牌的声明
【发布时间】:2018-11-03 13:59:31
【问题描述】:

您好,我曾尝试在 Spring Boot 中使用 jwt 令牌,但遇到了将自定义声明添加到 jwt 令牌中的问题。我想添加自定义声明,例如 issuer、audience、exp、sub、...user:{}、.. 如何将我的对象添加到标题和有效负载部分

【问题讨论】:

    标签: spring-mvc spring-boot jwt spring-security-oauth2


    【解决方案1】:

    我假设您使用的是 spring-security-oauth2。我没有得到How can I add my object into header and payload sections 的部分,但您可以使用TokenEnhancer 提到的in this tutorial。该教程中的示例 sn-p 如下所示:

    public class CustomTokenEnhancer implements TokenEnhancer {
        @Override
        public OAuth2AccessToken enhance(
         OAuth2AccessToken accessToken, 
         OAuth2Authentication authentication) {
            Map<String, Object> additionalInfo = new HashMap<>();
            additionalInfo.put("organization", authentication.getName() + randomAlphabetic(4));
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
            return accessToken;
        }
    }
    

    要获取更多信息,您可以使用 AuthorizationServerTokenServices

    tokenServices.getAccessToken(authentication).getAdditionalInformation();
    

    【讨论】:

    • 非常感谢。我会尝试使用其中一种方式。
    • 不客气。如果它解决了您的问题,请接受它作为答案。
    • 您好,我做到了,但 Jwt 遇到了另一个问题。当我获得当前用户身份验证时,它只返回用户名。如何从 OAuth2Authentication Jwt 获取全部用户信息
    • @NasibullohYandashev,我已经在线更新了答案
    • 这不会向 JWT Payload 或标头添加自定义声明。它只会将自定义 json 字段添加到最终的 json 令牌响应中
    【解决方案2】:

    我已经用下面的代码解决了:

    @Bean
        public JwtAccessTokenConverter tokenEnhancer() {
            KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(
                    new ClassPathResource("jwt.jks"),
                    keyStorePassword.toCharArray());
            // For getting user information in getPrincipal()
            DefaultUserAuthenticationConverter duac = new DefaultUserAuthenticationConverter();
            duac.setUserDetailsService(userDetailsService);
            DefaultAccessTokenConverter datc = new DefaultAccessTokenConverter();
            datc.setUserTokenConverter(duac);
    
            JwtAccessTokenConverter converter = new CustomAccessTokenConverter();
            converter.setAccessTokenConverter(datc); // IMPORTANT
            converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));
            return converter;
        }
    

    【讨论】:

      猜你喜欢
      • 2018-07-30
      • 2021-12-08
      • 1970-01-01
      • 2021-02-13
      • 2018-07-05
      • 2019-02-07
      • 2022-11-15
      • 2021-04-23
      • 2020-04-23
      相关资源
      最近更新 更多