使用OAuth2在带有社交功能的Spring Boot Web应用上注册

时间:2019-05-22 17:40:49

标签: spring spring-security-oauth2

我想用Facebook进行用户注册。我知道最好的方法是通过OAuth2。我正在尝试按照本指南https://www.baeldung.com/spring-security-5-oauth2-login进行整合,一切似乎都正常!

SecurityConfiguration类:

@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@EnableJpaRepositories(basePackageClasses = UserRepository.class)
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .formLogin()
                    .loginPage("/login")
                    .failureUrl("/login?error=true")
                    .and()
                .oauth2Login()
                    .loginPage("/login")
                    .failureUrl("/login?error=true")
                    .and()
                .logout()
                    .logoutSuccessUrl("/")
                    .deleteCookies("JSESSIONID")
                    .invalidateHttpSession(true);
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

登录控制器方法:

@GetMapping("/login")
public String getLoginPage(Model model, Principal principal) {
    if(principal != null && principal.getName() != null)
        return "redirect:/users/" + principal.getName();
    Iterable<ClientRegistration> clientRegistrations = null;
    ResolvableType type = ResolvableType.forInstance(clientRegistrationRepository)
            .as(Iterable.class);
    if (type != ResolvableType.NONE &&
            ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) {
        clientRegistrations = (Iterable<ClientRegistration>) clientRegistrationRepository;
    }

    clientRegistrations.forEach(registration ->
            oauth2AuthenticationUrls.put(registration.getClientName(),
                    authorizationRequestBaseUri + "/" + registration.getRegistrationId()));
    model.addAttribute("urls", oauth2AuthenticationUrls);
    return "login";
}

正如我所说的,它工作正常,当我单击“使用Facebook登录”按钮时,它将我重定向到Facebook,并在成功登录后将我重定向到我的Web应用程序。唯一的问题是我不知道如何使用这种方式进行注册...

我不知道我是否要做的只是创建一个重定向到Facebook的注册页面,并且在Facebook登录成功后,重定向请求被创建新用户的控制器拦截,或者是否还有另一个(更好)的方法。

0 个答案:

没有答案