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

使用Spring Security从JWT令牌中提取当前登录的用户信息

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

使用Spring Security从JWT令牌中提取当前登录的用户信息

您需要做的第一件事是在创建JWT时将用户信息存储在JWT内,然后在使用JWT时将其提取。我有一个类似的情况,我通过扩展双方解决它

TokenEnhancer
JwtAccessTokenConverter

我使用

TokenEnhancer
来将我的扩展类型的主体嵌入
CustomUserDetails
JWT其他信息中。

public class CustomAccessTokenEnhancer implements TokenEnhancer {    @Override    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {        Authentication userAuthentication = authentication.getUserAuthentication();        if (userAuthentication != null) { Object principal = authentication.getUserAuthentication().getPrincipal(); if (principal instanceof CustomUserDetails) {     Map<String, Object> additionalInfo = new HashMap<>();     additionalInfo.put("userDetails", principal);     ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo); }        }        return accessToken;    }}

然后

Authentication
在处理经过身份验证的请求时在构建对象时手动提取扩展的主体。

public class CustomJwtAccessTokenConverter extends JwtAccessTokenConverter {    @Override    public OAuth2Authentication extractAuthentication(Map<String, ?> map) {        OAuth2Authentication authentication = super.extractAuthentication(map);        Authentication userAuthentication = authentication.getUserAuthentication();        if (userAuthentication != null) { linkedHashMap userDetails = (linkedHashMap) map.get("userDetails"); if (userDetails != null) {     // build your principal here     String localUserTableField = (String) userDetails.get("localUserTableField");     CustomUserDetails extendedPrincipal = new CustomUserDetails(localUserTableField);     Collection<? extends GrantedAuthority> authorities = userAuthentication.getAuthorities();     userAuthentication = new UsernamePasswordAuthenticationToken(extendedPrincipal,  userAuthentication.getCredentials(), authorities); }        }        return new OAuth2Authentication(authentication.getOAuth2Request(), userAuthentication);    }}

以及将

AuthorizationServer
其捆绑在一起的配置。

@Configuration@EnableAuthorizationServerpublic class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {    @Autowired    private AuthenticationManager authenticationManager;    @Autowired    private UserDetailsService userDetailsService;    @Autowired    private DataSource dataSource;    @Bean    public JwtAccessTokenConverter accessTokenConverter() {        CustomJwtAccessTokenConverter accessTokenConverter = new CustomJwtAccessTokenConverter();        accessTokenConverter.setSigningKey("a1b2c3d4e5f6g");        return accessTokenConverter;    }    @Bean    public TokenStore tokenStore() {        return new JwtTokenStore(accessTokenConverter());    }    @Bean    @Primary    public DefaultTokenServices tokenServices() {        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();        defaultTokenServices.setTokenStore(tokenStore());        defaultTokenServices.setSupportRefreshToken(true);        return defaultTokenServices;    }    @Bean    public TokenEnhancer tokenEnhancer() {        return new CustomAccessTokenEnhancer();    }    @Bean    public PasswordEnprer passwordEnprer() {        return new BCryptPasswordEnprer();    }    @Override    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {        clients.jdbc(dataSource).passwordEnprer(passwordEnprer());    }    @Override    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter()));        endpoints     .tokenStore(tokenStore())     .tokenEnhancer(tokenEnhancerChain)     .authenticationManager(authenticationManager)     .userDetailsService(userDetailsService);    }    @Override    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {        security.passwordEnprer(passwordEnprer());        security.checkTokenAccess("isAuthenticated()");    }}

然后,我可以像这样访问我的资源控制器中的扩展主体

@RestControllerpublic class SomeResourceController {    @RequestMapping("/some-resource")    public ResponseEntity<?> someResource(Authentication authentication) {        CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();        return ResponseEntity.ok("woo hoo!");    }}

希望这可以帮助!



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

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

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