生成自定义jwt令牌并验证用户,Spring Security

时间:2018-06-29 18:18:34

标签: java authentication spring-security jwt

情况:我有另一个API的令牌,其中包含用户信息,并且用户已经登录。我想验证此用户信息(已提取)并使用我的spring安全应用程序生成令牌。

注意:我使用的是Jwt自定义附魔,对于新手发布方式表示抱歉。

我的安全配置:

@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();
}

1 个答案:

答案 0 :(得分:0)

实际上我解决了我自己的调试和搜索问题!

//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;

基本上,您要做的就是使用Oauth2Request生成身份验证并使用.createAccessToken()!

也许可以帮助其他人!