在我的Spring Boot + Security + Web应用程序中添加可选的Google登录

时间:2017-08-18 16:20:51

标签: spring spring-security oauth-2.0 spring-security-oauth2

我正在开发 Spring启动Web应用程序。我现在使用Spring Security使用自定义userDetailService工作注册和登录系统。

现在我想使用 Google帐户添加注册登录系统。我创建了 Google API密钥,并将其添加到application.properties。我认为没有必要在这里使用.yml propertie文件:

# ===============================
# = OAUTH2
# ===============================
security.oauth2.client.client-id=clientId Here
security.oauth2.client.client-secret=clientSecret here
security.oauth2.client.access-token-uri=https://www.googleapis.com/oauth2/v3/token
security.oauth2.client.user-authorization-uri=https://accounts.google.com/o/oauth2/auth
security.oauth2.client.token-name=oauth_token
security.oauth2.client.authentication-scheme=query
security.oauth2.client.client-authentication-scheme=form
security.oauth2.client.scope=profile
security.oauth2.resource.user-info-uri=https://www.googleapis.com/userinfo/v2/me
security.oauth2.resource.prefer-token-info=false

我以这种方式向 Spring Boot应用添加了 OAuth2 支持:

@SpringBootApplication
@EnableOAuth2Sso
public class WebApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }
}

现在我希望保持使用Google登录或使用网站帐户登录的可能性,但我只找到有关独特登录或多个提供商登录的手册(Facebook,Google,Twitter ..)

在我的SpringSecurity配置类中,我有这个。我认为我必须为Google创建一个authenticationProvider并将其链接到我的应用中的google访问网址,但我对此非常困惑:

    @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

            /**
             * Obtenemos información de persistencia
             */
            // @formatter:off
            auth
                //.authenticationProvider(googleOauth2AuthProvider())
                .userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder);
            // @formatter:on
    }
    ...
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        String[] anonymousRequest = { urls};

        http
        .authorizeRequests()
        //..other rules

2 个答案:

答案 0 :(得分:1)

您可以使用Spring Social或OAUTH2

来实现此目的

如果你想使用spring社交网站,请注意默认情况下在春季启动社交版中不支持Google,因此您必须执行一些额外的步骤。

  1. 添加Maven依赖项

    <dependency>
        <groupId>org.springframework.social</groupId>
        <artifactId>spring-social-google</artifactId>
        <version>1.0.0.RELEASE</version>
    </dependency>
    
  2. 添加GoogleAutoConfiguration类

  3. 在IDE(eclipse)中执行Ctrl + Shift + T并查找FacebookAutoConfiguration类,您应该可以在spring-autoconfigure.jar中的org.springframework.boot.autoconfigure.social包中找到它。复制此文件并将Google替换为Google。

    3.添加GoogleProperties

    在同一个包中添加以下类

    @ConfigurationProperties(prefix = "spring.social.google")
    
    public class GoogleProperties extends SocialProperties{
    

    使用您的Google API密钥更新application.properties

    Follow this link for complete description and step by step instruction

    希望它有所帮助!!

    如果您想使用OAUTH2 here is a working example

答案 1 :(得分:1)

您必须使用复合过滤器来配置所需的身份验证提供程序,例如:

private Filter ssoFilter() {
    CompositeFilter filter = new CompositeFilter();
    List<Filter> filters = new ArrayList<>();
    filters.add(ssoFilter(facebook(), "/login/facebook"));
    filters.add(ssoFilter(google(), "/login/google"));
    filter.setFilters(filters);
    return filter;
}

private Filter ssoFilter(ClientResources client, String path) {
    OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationFilter = new OAuth2ClientAuthenticationProcessingFilter(
            path);
    OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);

    oAuth2ClientAuthenticationFilter.setRestTemplate(oAuth2RestTemplate);
    UserInfoTokenServices tokenServices = new UserInfoTokenServices(client.getResource().getUserInfoUri(),
            client.getClient().getClientId());

    tokenServices.setRestTemplate(oAuth2RestTemplate);
    oAuth2ClientAuthenticationFilter.setTokenServices(tokenServices);
    return oAuth2ClientAuthenticationFilter;
}

其中:

@Bean
@ConfigurationProperties("google")
public ClientResources google() {
    return new ClientResources();
}

@Bean
@ConfigurationProperties("facebook")
public ClientResources facebook() {
    return new ClientResources();
}

class ClientResources {

    @NestedConfigurationProperty
    private AuthorizationCodeResourceDetails client = new AuthorizationCodeResourceDetails();


    @NestedConfigurationProperty
    private ResourceServerProperties resource = new ResourceServerProperties();

    public AuthorizationCodeResourceDetails getClient() {
        return client;
    }

    public ResourceServerProperties getResource() {
        return resource;
    }
}

最后,在HTTP安全配置中的BasicAuthenticationFilter之前添加过滤器:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        String[] anonymousRequest = { urls};

        http
        .authorizeRequests()
        //..other rules
        addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);

Ps:您的配置属性必须以@ConfigurationProperties("facebook")

中指定的值开头
facebook:
  client:
    clientId: yourCliendId
    clientSecret: yourClientSecret
    accessTokenUri: https://graph.facebook.com/oauth/access_token
    userAuthorizationUri: https://www.facebook.com/dialog/oauth
    tokenName: oauth_token
    authenticationScheme: query
    registeredRedirectUri: http://localhost:8083/app.html
    preEstablishedRedirectUri: http://localhost:8083/app.html
    clientAuthenticationScheme: form
  resource:
    userInfoUri: https://graph.facebook.com/me

这受益于此处提供的示例:https://github.com/spring-guides/tut-spring-boot-oauth2/tree/master/github