使用 Spring 安全授权的 OAuth2 数据创建自定义用户

Create custom User with OAuth2 data from authorization with Spring Security

我试图在我的应用程序中同时支持表单登录和 Facebook 身份验证,目的是创建一个 User 对象。使用 formLogin 我可以创建一个注册控制器并保留我的用户实体,但是我如何拦截来自 Facebook 的 OAuth2 身份验证以创建(或登录,如果它已经存在)一个用户实体?

这是我目前的安全配置:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/oauth2/**", "/webjars/**", "/users/signup", "/users/recover", "/users/reset/**", "/img/**", "/css/**", "/js/**").permitAll()
            .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/users/login")
                .successHandler(loginSuccessHandler())
                .permitAll()
                .and()
            .logout()
                .logoutUrl("/users/logout")
                .logoutSuccessUrl("/users/login?logout")
                .permitAll()
                .and()
            .oauth2Login()
                .defaultSuccessUrl("users/facebook");
    }

有没有办法创建一个 successHandler 或类似的方法来完成这个?

终于找到了解决方案,如前所述here you should configure your OAuth2 authorization with the spring-security-oauth2-autoconfigure package using the @ EnableOAuth2Sso annotation and then creating a PrincipalExtractor根据 OAuth2 提供商发送的数据构建您的用户实体。

这样您自己的模型对象将可以在以后的调用中通过 getPrincipal() 访问。