小编典典

我可以在颁发访问令牌时包含用户信息吗?

spring

我在一些oauth2实现中已经看到了有关授权服务器发出访问令牌时返回的响应的其他信息。我想知道是否有一种方法可以使用spring-security-oauth2来完成。我希望能够在访问令牌响应中包括一些用户权限,以便我的使用中的应用程序无需管理用户权限,但仍可以根据自己的安全上下文设置用户并应用其自身的任何spring-security检查。

  1. 我将如何获得有关访问令牌响应的信息?
  2. 如何在oauth2客户端上拦截该信息并在安全上下文中进行设置?
    我想另一个选择是使用JWT令牌,并与客户端应用程序共享适当的信息,以便它们可以从令牌中解析用户/权限,并在上下文中进行设置。这使我更加不舒服,因为我希望控制哪些客户端应用程序可以访问此信息(仅受信任的应用程序)和AFAIK,只有授权服务器和资源服务器才知道如何解析JWT令牌。

阅读 478

收藏
2020-04-13

共1个答案

小编典典

你将需要实现一个自定义TokenEnhancer,如下所示:

public class CustomTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        User user = (User) authentication.getPrincipal();
        final Map<String, Object> additionalInfo = new HashMap<>();

        additionalInfo.put("customInfo", "some_stuff_here");
        additionalInfo.put("authorities", user.getAuthorities());

        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

        return accessToken;
    }

}

并将其作为具有相应设置器的Bean添加到你的AuthorizationServerConfigurerAdapter中

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    // Some autowired stuff here

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // @formatter:off
        endpoints
            // ...
            .tokenEnhancer(tokenEnhancer());
        // @formatter:on
    }

    @Bean
    @Primary
    public AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        // ...
        tokenServices.setTokenEnhancer(tokenEnhancer());
        return tokenServices;
    }

    // Some @Bean here like tokenStore

    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new CustomTokenEnhancer();
    }

}

然后在控制器中(例如)

@RestController
public class MyController {

    @Autowired
    private AuthorizationServerTokenServices tokenServices;

    @RequestMapping(value = "/getSomething", method = RequestMethod.GET)
    public String getSection(OAuth2Authentication authentication) {
        Map<String, Object> additionalInfo = tokenServices.getAccessToken(authentication).getAdditionalInformation();

        String customInfo = (String) additionalInfo.get("customInfo");
        Collection<? extends GrantedAuthority> authorities = (Collection<? extends GrantedAuthority>) additionalInfo.get("authorities");

        // Play with authorities

        return customInfo;
    }

}

我个人使用JDBC TokenStore,所以我的“一些自动装配的东西在这里”对应于某些@Autowired数据源,PasswordEncoder和不对应的东西。

2020-04-13