栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

你将需要实现一个自定义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@EnableAuthorizationServerprotected 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();    }}

然后在控制器中(例如)

@RestControllerpublic 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数据源,PasswordEnprer和不对应的东西。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/400477.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号