使用 Spring Security(非 OAuth)使用登录名、密码和 Facebook

我已经使用 Spring Security 使用登录名和密码实现了注册和身份验证。我使用本教程做到了这一点。但现在我想使用 Facebook Id 提供注册和身份验证。我将在移动应用程序上获取 Facebook 用户的访问令牌,然后将此访问令牌发送到我的 Spring 服务器(因此 OAuth 不适合),使用 Facebook API 对其进行验证,并获取 Facebook 用户 ID。请注意,Users我的数据库中已经有包含user_id, login, password,fb_id列的表,因此注册有两种变体:要么用户有登录名和密码,要么用户只有 Facebook 帐户,我将使用他的 Facebook id。


最后,我只需要对该用户进行身份验证并返回给他 JWT 令牌。


已经存在的代码。


安全配置:


@Configuration

@EnableWebSecurity

@EnableGlobalMethodSecurity(

        securedEnabled = true,

        jsr250Enabled = true,

        prePostEnabled = true

)

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired

    private CustomUserDetailsService customUserDetailsService;


    @Autowired

    private JwtAuthenticationEntryPoint unauthorizedHandler;


    @Bean

    public JwtAuthenticationFilter jwtAuthenticationFilter() {

        return new JwtAuthenticationFilter();

    }


    @Override

    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {

        authenticationManagerBuilder

                .userDetailsService(customUserDetailsService)

                .passwordEncoder(passwordEncoder());

    }


    @Bean(BeanIds.AUTHENTICATION_MANAGER)

    @Override

    public AuthenticationManager authenticationManagerBean() throws Exception {

        return super.authenticationManagerBean();

    }


    @Bean

    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();

    }



缥缈止盈
浏览 164回答 1
1回答

繁星coding

您可以创建一个 APIid_token从请求正文中的客户端获取。调用 facebook 的 API 来验证id_token并获取用户的详细信息。在数据库中保存或更新用户。验证用户创建并返回 JWT这是一个示例代码 -@PostMapping("/signin/facebook")public ResponseEntity<?> signInWithFacebook(@Valid @RequestBody FBLoginRequest loginRequest) {&nbsp; &nbsp; // Call facebook's API to validate id_token and get user's details&nbsp; &nbsp; // Register new user (Note: Also add code to check if a user already exists with the given facebookId )&nbsp; &nbsp; User user = new User(fbName, fbID,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; emailId, null);&nbsp; &nbsp; Role userRole = roleRepository.findByName(RoleName.ROLE_USER)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .orElseThrow(() -> new AppException("User Role not set."));&nbsp; &nbsp; user.setRoles(Collections.singleton(userRole));&nbsp; &nbsp; User result = userRepository.save(user);&nbsp; &nbsp; // Authenticate User&nbsp; &nbsp; UserPrincipal userPrincipal = UserPrincipal.create(result);&nbsp; &nbsp; PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(userPrincipal, null, userPrincipal.getAuthorities());&nbsp; &nbsp; SecurityContextHolder.getContext().setAuthentication(authentication);&nbsp; &nbsp; // Generate and return token&nbsp; &nbsp; String jwt = tokenProvider.generateToken(authentication);&nbsp; &nbsp; return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));}我没有添加调用 facebook 的 API 的代码。但这应该很容易实现。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java