Spring Security 使用多种身份验证方法的Web安全设置

nsc4cvqm  于 2023-06-23  发布在  Spring
关注(0)|答案(2)|浏览(98)

我正在使用Spring Boot构建一个用于学习目的的用户身份验证微服务。我已经分别开发了3种不同的用户身份验证方法作为3个不同的项目(一个使用PostgreSQL数据库和JWT身份验证,另一个使用OAuth2,另一个使用LDAP)。现在我需要把这3个作为一个单一的服务。我已经设置了一些步骤。
目前我有以下几点:
这是我的SecurityConfigure.java文件:

package com.persistent.userauthentication.security;

import com.persistent.userauthentication.filters.JwtRequestFilter;
import com.persistent.userauthentication.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfigure extends WebSecurityConfigurerAdapter {

    @Configuration
    @Order(1)
    public static class JwtWebSecurityConfig extends WebSecurityConfigurerAdapter{
        @Autowired
        private AuthService authService;

        @Autowired
        private JwtRequestFilter jwtRequestFilter;

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

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .csrf().disable()
                .requestMatchers()
                    .antMatchers("/jwt/**")
                    .and()
                .authorizeRequests()
                    .antMatchers("/jwt/authenticate").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS); //since we don't want to manage sessions

            http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
        }

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

        @Bean
        public PasswordEncoder passwordEncoder(){
            return NoOpPasswordEncoder.getInstance();
        }
    }

    @Configuration
    @Order(2)
    public static class LdapSecurityConfig extends WebSecurityConfigurerAdapter{
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/ldapauth/**")
                .authorizeRequests()
                    .anyRequest().fullyAuthenticated()
                    .and()
                .formLogin();
        }

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

    @Configuration
    @Order(3)
    public static class Oauth2SecurityConfig extends WebSecurityConfigurerAdapter{

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

这是我的AuthController.java(控制器)文件:

package com.persistent.userauthentication.controller;

import com.persistent.userauthentication.model.AuthenticationRequest;
import com.persistent.userauthentication.model.AuthenticationResponse;
import com.persistent.userauthentication.service.AuthService;
import com.persistent.userauthentication.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

@RestController
public class AuthController {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtUtil jwtTokenUtil;

    @RequestMapping(value = "/jwt/hello", method = RequestMethod.GET)
    public String Hello(){
        return "basic auhentication successfull";
    }

    @GetMapping("/googleauth/hello")
    public String GooglAauth(){
        return "google authentication successful!";
    }

    @RequestMapping(value = "/ldapauth/hello", method = RequestMethod.GET)
    public String LdapAuth(){
        return "ldap authentication successful!";
    }

    @RequestMapping(value = "/jwt/authenticate", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest) throws Exception {

        try {
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword())
            );
        } catch (BadCredentialsException e){
            throw new Exception("username or password is incorrect!", e);
        }

        final UserDetails userDetails = authService.loadUserByUsername(authenticationRequest.getUsername());

        final String jwt = jwtTokenUtil.generateToken(userDetails);

        return ResponseEntity.ok(new AuthenticationResponse(jwt));
    }

    @RequestMapping(value = "/jwt/extendtoken", method = RequestMethod.POST)
    public ResponseEntity<?> createNewAuthenticationToken(@RequestHeader("Authorization") String token) throws Exception {

        final String jwt = jwtTokenUtil.refreshToken(token);

        return ResponseEntity.ok(new AuthenticationResponse(jwt));
    }
}

目前,/jwt/hello(带有Authorization头部和生成的JWT代码)、/jwt/authenticatejwt/extendtoken端点工作正常。
现在我需要为/googleauth/hello端点设置OAuth2身份验证服务,为/ldapauth/hello设置LDAP身份验证服务。
当我调用端点/googleauth/hello时,它也会重定向到LDAP登录页面,而不是Google帐户选择页面。

9cbw7uwe

9cbw7uwe1#

最后,这个解决方案对我有效。我不得不改变我的安全配置如下。

@Configuration
@EnableWebSecurity
public class SecurityConfigure extends WebSecurityConfigurerAdapter {

    @Configuration
    @Order(1)
    public static class JwtWebSecurityConfig extends WebSecurityConfigurerAdapter{
        @Autowired
        private AuthService authService;

        @Autowired
        private JwtRequestFilter jwtRequestFilter;

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

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .csrf().disable()
                    .requestMatchers().antMatchers("/jwt/**")
                    .and()
                    .authorizeRequests().antMatchers("/jwt/authenticate").permitAll()
                    .anyRequest().authenticated()
                    .and().sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

            http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

        }

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

        @Bean
        public PasswordEncoder passwordEncoder(){
            return NoOpPasswordEncoder.getInstance();
        }
    }

    @Configuration
    @Order(2)
    public static class LdapSecurityConfig extends WebSecurityConfigurerAdapter{
                @Override
                public void configure(AuthenticationManagerBuilder auth) throws Exception {
                    auth
                            .ldapAuthentication()
                            .userDnPatterns("uid={0},ou=people")
                            .groupSearchBase("ou=groups")
                            .contextSource()
                            .url("ldap://localhost:8389/dc=springframework,dc=org")
                            .and()
                            .passwordCompare()
                            .passwordEncoder(new BCryptPasswordEncoder())
                            .passwordAttribute("userPassword");
                }

                @Override
                protected void configure(HttpSecurity http) throws Exception {
                    http
                            .csrf().disable()
                            .requestMatchers().antMatchers("/ldap/**","/login")
                            .and()
                            .authorizeRequests().antMatchers("/login").permitAll()
                            .anyRequest().fullyAuthenticated()
                            .and()
                            .formLogin();
                }
    }

    @Configuration
    @Order(3)
    public static class Oauth2SecurityConfig extends WebSecurityConfigurerAdapter{

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .csrf().disable()
                    .requestMatchers().antMatchers("/google/**","/oauth2/**","/login/oauth2/**")
                    .and()
                    .authorizeRequests().antMatchers("/oauth2/**","/login/oauth2/**").permitAll()
                    .anyRequest().fullyAuthenticated()
                    .and()
                    .oauth2Login();
        }
    }

}
xn1cxnb4

xn1cxnb42#

在spring安全配置类中具有基本和jwt身份验证的示例

@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/**").authenticated()
            .antMatchers("/swagger-ui/**").authenticated()
            .antMatchers("/**").permitAll()
            .and().httpBasic().and().oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
    return http.build();
}

相关问题