spring-boot - 将 OAuth2 登录附加到 Spring Boot 应用程序中的现有用户

标签 spring-boot oauth-2.0 google-oauth spring-security-oauth2 spring-social

我有一个“仅限邀请”的 Spring Boot 应用程序。 IE。用户会收到一个注册链接,但没有“注册”功能。这工作正常,用户使用他们的用户名和密码登录。

我想允许使用 OAuth2 作为补充登录方法登录 FaceBook 和 Google。这将涉及以某种方式将现有用户映射到他们的社交帐户。用户及其密码存储在 MySQL 数据库中。我找到了很多关于 OAuth2 和 Spring Boot 的文章,但没有一篇文章专门针对这个用例。

我可以创建 Google OAuth2 token /客户端密码等,但我如何设计流程以仅允许现有用户使用他们的社交帐户登录?

用户名由用户自己选择,因此不一定与他们的电子邮件相同。

在这种情况下,我是否需要创建自定义身份验证流程? 我是否需要将身份验证机制从 cookie 更改为 JWT token ?

最佳答案

我发现自己处于类似情况,我需要知道我收到的 OAuth 请求是否来自已通过身份验证的用户。

虽然在我的例子中我需要知道这一点,因为我希望用户能够将他们现有的帐户“链接”到社交帐户。

我最终做的是实现一个只有一个方法的 OAuth2UserService:

public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException{

    // this will be null if the OAuth2UserRequest is not from an authenticated user 
    // otherwise, it would contain the current user's principle which you can use to check if the OAuth request should be handled or not
    Authentication currentAuth =  SecurityContextHolder.getContext().getAuthentication();

    // for example: 
    // if(currentAuth == null)
    //     throw new OAuth2AuthenticationException(OAuth2ErrorCodes.ACCESS_DENIED);

    // Use the default service to load the user
    DefaultOAuth2UserService defaultService = new DefaultOAuth2UserService();
    OAuth2User defaultOAuthUser = defaultService.loadUser(userRequest);

    // here you might have extra logic to map the defaultOAuthUser's info to the existing user
    // and if you're implementing a custom OAuth2User you should also connect them here and return the custom OAuth2User

    return defaultOAuthUser;
}

然后只需在您的安全配置中注册自定义 OAuth2UserService:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // your existing config
            .oauth2Login()
            .userInfoEndpoint()
            .userService(oauthUserService())
        ;
    }

    @Bean
    public OAuth2UserService oauthUserService(){
        return new MyCustomOAuth2UserService();
    }

关于spring-boot - 将 OAuth2 登录附加到 Spring Boot 应用程序中的现有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59224564/

相关文章:

java - Spring boot PropertySourcesPlaceHolderConfigurer 与 @ProperySource

oauth-2.0 - 如何在 Rust 中使用 google_speech1 发送语音到文本请求?

java - 使用Google登录授权YouTube数据API

json - 从 Golang 中的模数和指数创建公钥

Spring Boot JPA - 配置自动重新连接

java - 无法运行docker镜像

docker-compose - 外部化 spring application.properties

google-chrome-extension - 是否可以使用 Chrome App Indentity Api 获取 Id token ?

ruby-on-rails - 设计/谷歌 OAuth 2 : Not found. 认证通路

google-api - Google Drive API 1.8.1 - 大文件上传/下载问题