首页 > 解决方案 > Spring + LDAP 身份验证 + Google 登录

问题描述

我正在尝试实现LDAP 身份验证Google 登录,但我不知道如何将有关我的用户的信息从前端发送到后端。

我在前端使用 React.JS,当我使用 npm 的react-google-login包登录时,我会从 Google 获得一些信息(例如电子邮件、全名等)。当我使用 LDAP 登录时,我什么也没有得到(chrome 中显示了一个 JSESSIONID cookie,但 Spring 的响应数据中没有 cookie。)我可以成功登录两者但我怎么知道哪个人是从前端发送请求到后端吗?

在不使用 React 的情况下,如果我从 Chrome 或 Postman 向 spring 发送请求(如果我将 JSESSIONID cookie 添加到 Postman),如果用户使用 LDAP 登录,我可以使用SecurityContextHolder.getContext().getAuthentication()对用户进行身份验证,并且从如果用户使用 Google Sign in 登录,则为 OAuth2USer对象。但问题是如何从 React 发送相同的参数?

我正在寻找从 Spring 获取 JWT 作为响应,因此我只能将 JWT 令牌发送到后端进行授权,但我无法弄清楚如何在 LDAP 身份验证和 Google 身份验证中发送它,并且不知道是否那将是矫枉过正。

到目前为止,我在 Spring 中的代码:

网络安全配置类

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final PasswordEncoder passwordEncoder;
    private final UserDetailsServiceImpl userDetailsServiceImpl;

    @Autowired
    public WebSecurityConfig(PasswordEncoder passwordEncoder, UserDetailsServiceImpl userDetailsService) {
        this.passwordEncoder = passwordEncoder;
        this.userDetailsServiceImpl = userDetailsService;
    }

    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return new AuthenticationFailureHandlerImpl();
    }

    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setPasswordEncoder(passwordEncoder);
        provider.setUserDetailsService(userDetailsServiceImpl);
        return provider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .csrf().disable()
                .authorizeRequests()
                    .antMatchers("/user/authenticate", "/login", "/user/me").permitAll()
                    .antMatchers("/user/add").hasRole(ADMIN.name())
                    .anyRequest().authenticated()
                .and()
                .formLogin()
                    .defaultSuccessUrl("/", true)
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .failureHandler(authenticationFailureHandler())
                .and()
                .logout()
                    .logoutUrl("/logout")
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
                    .clearAuthentication(true)
                    .invalidateHttpSession(true)
                    .deleteCookies("JSESSIONID")
                    .logoutSuccessUrl("/login")
                .and()
                .oauth2Login();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .authenticationProvider(daoAuthenticationProvider())
                .ldapAuthentication()
                    .userDnPatterns("uid={0},ou=people")
                    .groupSearchBase("ou=groups")
                    .contextSource()
                        .url("ldap://localhost:8389/dc=springframework,dc=org")
                        .and()
                    .passwordCompare()
                        .passwordEncoder(passwordEncoder)
                        .passwordAttribute("userPassword");
    }
}

在控制器中查找用户的方法

   public User findUser(@AuthenticationPrincipal OAuth2User user) {
        Optional<User> foundUser;
        if (user == null) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            foundUser = userRepository.findUserByUserID(((UserDetailsImpl) auth.getPrincipal()).getUserID());
        }
        else {
            foundUser = userRepository.findUserByEmail(user.getAttributes().get("email").toString());
        }

        return foundUser.get();
    }

标签: spring-bootauthenticationldapgoogle-oauth

解决方案


推荐阅读