【问题标题】:Generate custom jwt-token and Authenticate user, Spring Security生成自定义 jwt-token 并验证用户,Spring Security
【发布时间】:2018-12-08 23:35:27
【问题描述】:

情况:我有一个来自另一个 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();
}

【问题讨论】:

    标签: java authentication spring-security jwt


    【解决方案1】:

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

    //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()!

    也许它可以帮助别人!

    【讨论】:

      猜你喜欢
      • 2019-02-07
      • 2018-05-17
      • 2014-04-20
      • 2014-12-13
      • 2015-10-12
      • 2022-01-15
      • 2013-03-29
      • 2021-01-24
      • 2017-12-25
      相关资源
      最近更新 更多