繁体   English   中英

Spring Boot OAuth2手动创建新的JWT令牌

[英]Spring Boot OAuth2 manually create new JWT token

在我的Spring Boot应用程序中,我已经使用JWT令牌配置了Spring OAuth2服务器。

此外,我添加了Spring Social配置,以便能够通过各种社交网络(如Twitter,Facebook等)对用户进行身份验证。

这是我的SpringSocial配置:

@Configuration
@EnableSocial
public class SocialConfig extends SocialConfigurerAdapter {

    @Bean
    public ProviderSignInController providerSignInController(ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository usersConnectionRepository) {
        return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new SimpleSignInAdapter(authTokenServices, "client_id", userService));
    }

...

}

此外,基于回答问题的答案: 集成Spring Security OAuth2和Spring Social,我已经实现了SimpleSignInAdapter ,以便使用3rdparty Social Networks处理成功的身份验证:

public class SimpleSignInAdapter implements SignInAdapter {

    final static Logger logger = LoggerFactory.getLogger(SimpleSignInAdapter.class);

    public static final String REDIRECT_PATH_BASE = "/#/login";
    public static final String FIELD_TOKEN = "access_token";
    public static final String FIELD_EXPIRATION_SECS = "expires_in";

    private final AuthorizationServerTokenServices authTokenServices;
    private final String localClientId;
    private final UserService userService;

    public SimpleSignInAdapter(AuthorizationServerTokenServices authTokenServices, String localClientId, UserService userService){
        this.authTokenServices = authTokenServices;
        this.localClientId = localClientId;
        this.userService = userService;
    }

    @Override
    public String signIn(String userId, Connection<?> connection, NativeWebRequest request) {

        UserDetails userDetails = loadUserById(Long.parseLong(userId));

        OAuth2AccessToken oauth2Token = authTokenServices.createAccessToken(convertAuthentication(userDetails)); 
        String redirectUrl = new StringBuilder(REDIRECT_PATH_BASE)
            .append("?").append(FIELD_TOKEN).append("=")
            .append(encode(oauth2Token.getValue()))
            .append("&").append(FIELD_EXPIRATION_SECS).append("=")
            .append(oauth2Token.getExpiresIn())
            .toString();    

        return redirectUrl;
    }

    private OAuth2Authentication convertAuthentication(UserDetails userDetails) {
        OAuth2Request request = new OAuth2Request(null, localClientId, null, true, null, null, null, null, null);
        return new OAuth2Authentication(request, new UsernamePasswordAuthenticationToken(userDetails, "N/A", userDetails.getAuthorities()));
    }

    private String encode(String in) {
        String res = in;
        try {
            res = UriUtils.encode(in, "UTF-8");
        } catch(UnsupportedEncodingException e){
            logger.error("ERROR: unsupported encoding: " + "UTF-8", e);
        }
        return res;
    }

    public UserDetails loadUserById(Long id) throws UsernameNotFoundException {
        User user = userService.findUserById(id);
        if (user == null) {
            throw new UsernameNotFoundException("User " + id + " not found.");
        }

        Set<Permission> permissions = userService.getUserPermissions(user);
        return new DBUserDetails(user, permissions);
    }

}

一切正常,除了一件事 - 以下代码行产生普通的OAuth2访问令牌:

OAuth2AccessToken oauth2Token = authTokenServices.createAccessToken(convertAuthentication(userDetails));

但我需要创建JWT令牌。

如何创建或转换此令牌为基于JWT? 我想我可以为此目的使用JwtAccessTokenConverter类,但现在不知道如何。

调试后我找到了一个解决方案:

private final TokenEnhancer tokenEnhancer;

...
OAuth2Authentication authentication = convertAuthentication(userDetails);
OAuth2AccessToken accessToken = authTokenServices.createAccessToken(authentication); 
accessToken = tokenEnhancer.enhance(accessToken, authentication);

在我需要自己的自定义JWT令牌后,这对我有用。

DefaultTokenServices service = new DefaultTokenServices(); 
    service.setTokenStore(jwtAccessTokenConverter);
    service.setTokenEnhancer(jwtAccessTokenConverter);
    OAuth2AccessToken token = service.createAccessToken(authentication);

自动装载jwtAccessTokenConverter

@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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