Spring oauth2登录 - 谷歌/ Facebook工作,但也需要基本的基于表单的身份验证

时间:2018-04-23 08:58:29

标签: spring spring-security oauth-2.0

我让我的Spring项目在Google / Facebook登录时运行正常。

http://www.baeldung.com/spring-security-5-oauth2-login

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
         .anyRequest().authenticated()
         .and()
         .oauth2Login();
    }
}

如果我只想要基于表单的登录(即用户名/密码,没有oauth),我会执行以下操作:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/private").authenticated()
            .antMatchers("/accounts/**").hasAnyRole(Role.ADMIN,Role.MANAGER,Role.USER)
            .antMatchers("/books/**").hasAnyRole(Role.MANAGER,Role.USER)
            .and()
        .httpBasic()
            .and()
        .logout()
             .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
             .clearAuthentication(true)
             .deleteCookies("JSESSIONID")
             .logoutSuccessUrl("/loggedOut").deleteCookies("JSESSIONID")
             .invalidateHttpSession(true)
             .permitAll()
    }
}

基于表单的登录也可以正常工作。

但如何将两者结合起来?即用户可以使用他们的用户名/密码对或他们的社交媒体帐户登录吗?

1 个答案:

答案 0 :(得分:1)

您需要添加到序列中的一件事是:当用户通过社交登录登录时,您必须与您自己的(有效会话)“交换”该身份验证,因此您可以像处理基于表单的登录一样处理配置(也可以不需要发出access_token)。

最佳!