成功的OAuth2登录后,Spring Social Google用作提供商的签名失败



我需要同时将Facebook和Google用作提供商中的OpenID Sing。如文档中所述,我已经将它们与春季安全性集成在一起,并查看示例应用程序。

我成功配置了Facebook。

问题是我尝试使用Google进行身份验证:

OAuth2AuthenticationService.getAuthToken():

...
AccessGrant accessGrant = getConnectionFactory().getOAuthOperations().exchangeForAccess(code, returnToUrl, null);

在这一点上,我可以看到AccessGrant包含一个访问,因此到目前为止似乎是正确的。它在以下通话中失败:

// TODO avoid API call if possible (auth using token would be fine)
Connection<S> connection = getConnectionFactory().createConnection(accessGrant);

createConnection()最终致电GoogleConnectionFactory.extractProviderUserId(AccessGrant accessGrant)

Google api = ((GoogleServiceProvider)getServiceProvider()).getApi(accessGrant.getAccessToken());
UserProfile userProfile = getApiAdapter().fetchUserProfile(api);
...

getApiAdapter().fetchUserProfile(Google)-> google.plusOperations().getGoogleProfile();抛出403例外:

org.springframework.web.client.HttpClientErrorException: 403 Forbidden

为什么它不能获得Google Profile?显然,我设置的范围以及向用户提示的内容是正确的...

完整的项目可在此处提供:https://github.com/codepentent/spring-boot-social-signin

摘录摘自config:

SecurityConfig

@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/secure*").authenticated()
                .and()
            .formLogin()
                .loginPage("/login").permitAll()
                //.loginProcessingUrl("/secure-home")
                .failureUrl("/login?param.error=bad_credentials")
                .and()
            .logout()
                .logoutUrl("/logout")
                .deleteCookies("JSESSIONID")
                .and()
            /*.rememberMe()
                .and()*/
            .apply(new SpringSocialConfigurer());
    }
    @Bean
    public SocialUserDetailsService socialUserDetailsService(){
        return new SocialUserDetailsService(){
            @Override
            public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException{
                return new SimpleSocialUserDetails(userId);
            }
        }
    }
}

SocialConfig

@Configuration
@EnableSocial
class SocialConfig extends SocialConfigurerAdapter{
    @Override
    void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) {
        FacebookConnectionFactory fcf = new FacebookConnectionFactory(env.getProperty("facebook.clientId"), env.getProperty("facebook.clientSecret"))
        fcf.setScope("public_profile,email")
        cfConfig.addConnectionFactory(fcf)
        GoogleConnectionFactory gcf = new GoogleConnectionFactory(env.getProperty("google.clientId"), env.getProperty("google.clientSecret"))
        gcf.setScope("openid https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo#email https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/tasks https://www-opensocial.googleusercontent.com/api/people https://www.googleapis.com/auth/plus.login");
        cfConfig.addConnectionFactory(gcf);
    }
    @Bean
    @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
    Facebook facebook(ConnectionRepository repository) {
        Connection<Facebook> connection = repository.findPrimaryConnection(Facebook.class);
        return connection != null ? connection.getApi() : null;
    }
    @Bean
    @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
    Google google(ConnectionRepository repository) {
        Connection<Google> connection = repository.findPrimaryConnection(Google.class);
        return connection != null ? connection.getApi() : null;
    }
    @Override
    UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
        //return new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
        InMemoryUsersConnectionRepository rep = new InMemoryUsersConnectionRepository(connectionFactoryLocator)
        rep.setConnectionSignUp(new ConnectionSignUp(){
            public String execute(Connection<?> connection){
                Facebook facebook = (Facebook)connection.getApi();
                String [] fields = [ "id", "email",  "first_name", "last_name", "about" , "gender" ];
                User userProfile = facebook.fetchObject(connection.getKey().getProviderUserId(), User.class, fields);
                return userProfile.getEmail();
            }
        })
        return rep;
    }
    @Override
    UserIdSource getUserIdSource() {
        return new AuthenticationNameUserIdSource()
    }
}

修复了,我必须在Google开发人员控制台上启用Google API。

最新更新