简体   繁体   中英

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. I want to authenticate this user info (already extracted) and generate a token with my spring security application.

Notes: I'm using Jwt custom enchancer and sorry for newbie way of posting.

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

Maybe it could help someone else!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM