【问题标题】:Spring Security OAuth 2: How to get access token and additional data after oauth/token requestSpring Security OAuth 2:如何在 oauth/token 请求后获取访问令牌和附加数据
【发布时间】:2014-09-17 11:15:44
【问题描述】:

我正在使用 Spring Security 和 Oauth 2.0 身份验证协议保护 REST 服务。

我已经实现了一个 MVC Spring 应用程序,它运行良好。 客户端通过提供客户端凭据(client_id 和 client_secret)和用户凭据(用户名和密码)调用定义在 servlet-config.xml 中的 outh/token 服务向服务器请求 AccessToken:

<http pattern="/oauth/token" create-session="stateless"
    authentication-manager-ref="clientAuthenticationManager"
    xmlns="http://www.springframework.org/schema/security" > 
    <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
    <anonymous enabled="false" />
    <http-basic entry-point-ref="clientAuthenticationEntryPoint" />
    <custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER" /> 
    <access-denied-handler ref="oauthAccessDeniedHandler" />
 </http>

如果凭据有效,客户端将获得一个访问令牌,如下所示:

{
    "value": "b663f10d-553d-445b-afde-e9cd84066a1c",
    "expiration": 1406598295994,
    "tokenType": "bearer",
    "refreshToken": {
        "value": "36737abf-24bd-4b86-ad22-601f4d5cdee4",
        "expiration": 1408890295994
    },
    "scope": [],
    "additionalInformation": {},
    "expiresIn": 299999,
    "expired": false
}

我想要一个回复,其中还包含这样的用户详细信息:

{
        "value": "b663f10d-553d-445b-afde-e9cd84066a1c",
        "expiration": 1406598295994,
        "tokenType": "bearer",
        "refreshToken": {
            "value": "36737abf-24bd-4b86-ad22-601f4d5cdee4",
            "expiration": 1408890295994
        },

        "additionalInformation": {},
        "expiresIn": 299999,
        "expired": false,

        "USER_ID": "1",
        "USER_ROLE": "admin",
        "OTHER DATA..."
    }

有人知道实现这个的方法吗?

我已经在谷歌上搜索了很多,但我没有找到实现类似场景的示例。如果这个问题听起来很愚蠢,我很抱歉,但我是 Spring Security 的新手。

【问题讨论】:

    标签: spring spring-security oauth-2.0


    【解决方案1】:

    对于最近检查解决方案的人来说,this 也是一个很好的解决方案。

    @GetMapping("/token")
    @ResponseBody
    public String userinfo(@RegisteredOAuth2AuthorizedClient("${YOUR_CLIENT}") OAuth2AuthorizedClient authorizedClient) {
        return authorizedClient.getAccessToken().getTokenValue();
    }
    

    【讨论】:

      【解决方案2】:

      这就是我实现与您的场景类似的方式。

      1) 创建自定义令牌增强器:

      public class CustomTokenEnhancer implements TokenEnhancer {
      
          @Override
          public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
      
              final Map<String, Object> additionalInfo = new HashMap<>();
      
              User user = (User) authentication.getPrincipal();
      
              additionalInfo.put("user_id", user.getId());
              additionalInfo.put("business_id", user.getBusinessId());
      
              ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
      
              return accessToken;
          }
      
      }
      

      2) 配置中的用户自定义令牌增强器。

      @Override
      public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
          endpoints
              .tokenStore(tokenStore())
              .tokenEnhancer(tokenEnhancerChain())
              .authenticationManager(authenticationManager)
              .accessTokenConverter(jwtAccessTokenConverter());
      }
      
      /**
       * Creates a chain of the list of token enhancers.
       * @return
       * 
       * @since 0.0.1
       * 
       * @author Anil Bharadia
       */
      public TokenEnhancerChain tokenEnhancerChain() {
          TokenEnhancerChain chain = new TokenEnhancerChain();
          chain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter()));
          return chain;
      }
      
      /**
       * Get the new instance of the token enhancer.
       * @return
       */
      @Bean
      public TokenEnhancer tokenEnhancer() {
          return new CustomTokenEnhancer();
      }
      

      就是这样。下次您请求令牌时,您将获得带有附加信息的令牌。

      【讨论】:

        猜你喜欢
        • 2011-09-19
        • 2019-10-01
        • 1970-01-01
        • 2014-08-25
        • 1970-01-01
        • 2016-07-18
        • 2019-07-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多