[英]Generate custom jwt-token and Authenticate user, Spring Security
Situation: I have a token from another API that contains user info and user is already logged. 情况:我从另一个包含用户信息的API中获得了一个令牌,并且用户已经被登录。 I want to authenticate this user info (already extracted) and generate a token with my spring security application.
我想验证此用户信息(已提取)并用我的spring安全应用程序生成令牌。
Notes: I'm using Jwt custom enchancer and sorry for newbie way of posting. 注意:我使用的是Jwt自定义附魔,对于新手发布方式,我们深表歉意。
My security conf: 我的安全配置:
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter()));
endpoints.tokenStore(tokenStore()).tokenEnhancer(tokenEnhancerChain).reuseRefreshTokens(false)
.exceptionTranslator(loggingExceptionTranslator()).authenticationManager(authenticationManager);
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
accessTokenConverter.setSigningKey(properties.getAuth().getSigningKey());
return accessTokenConverter;
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public TokenEnhancer tokenEnhancer() {
return new PlaceTokenEnhancer();
}
Actually I solved my own problem debugging and searching! 实际上,我解决了自己的调试和搜索问题!
//load full user info (custom method)
UserDetails userDetails = placeUserDetailsService.loadUserByUsername(responseUser.getEmail());
Set<String> scope = new HashSet<>();
scope.add("read"); scope.add("write");
OAuth2Request auth2Request = new OAuth2Request(null, "smthg", userDetails.getAuthorities(), true,
scope, null, null, null, null);
//Custom OAuth2Token
PlaceAuthenticationToken placeAuthenticationToken = new PlaceAuthenticationToken(userDetails, userDetails.getAuthorities());
placeAuthenticationToken.setAuthenticated(true);
placeAuthenticationToken.setDetails(new WebAuthenticationDetails(request));
OAuth2Authentication auth = new OAuth2Authentication(auth2Request, placeAuthenticationToken);
auth.setAuthenticated(true);
auth.setDetails(placeAuthenticationToken.getDetails());
accessToken = authServer.createAccessToken(auth);
DefaultOAuth2AccessToken tkn = (DefaultOAuth2AccessToken) accessToken;
tkn.setRefreshToken(null);
accessToken = tkn;
Basically All you have to do is generate Authentication using Oauth2Request and use .createAccessToken()! 基本上,您要做的就是使用Oauth2Request生成身份验证并使用.createAccessToken()!
Maybe it could help someone else! 也许可以帮助别人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.