Spring Security 5.7 最新配置细节(直接就能用),WebSecurityConfigurerAdapter标横线 已废弃

在最新、独立的 Spring Security 5.7 版本,还是更新了不少内容,之前的 WebSecurityConfigurerAdapter 已经被废弃了,大家在使用的时候,可以参考下面的配置文件。
另外提醒一句,在最新的 Spring Boot 版本中的 Spring Security 并不一定也是最新版本,这个在实际开发中,需要留意一下哈。
此时,Spring Security 就不需要再去重写 configure() 方法了,直接通过 filterChain() 方法就能使用 HttpSecurity 来配置相关信息,非常方便。
官方参考文档中,也写得非常明白了,建议「逐字、逐句阅读」,供参考:Spring Security without the WebSecurityConfigurerAdapter

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity    // 添加 security 过滤器
@EnableGlobalMethodSecurity(prePostEnabled = true)    // 启用方法级别的权限认证
public class SpringSecurityConfig {
    @Autowired
    private XxxUserService xxxUserService;

    // 权限不足错误信息处理,包含认证错误与鉴权错误处理
    @Autowired
    private JwtAuthError jwtAuthError;

    // jwt 校验过滤器,从 http 头部 Authorization 字段读取 token 并校验
    @Bean
    public JwtAuthFilter authFilter() throws Exception {
        return new JwtAuthFilter();
    }

    /**
     * 密码明文加密方式配置
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 获取AuthenticationManager(认证管理器),登录时认证使用
     * @param authenticationConfiguration
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                // 基于 token,不需要 csrf
                .csrf().disable()
                // 基于 token,不需要 session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 设置 jwtAuthError 处理认证失败、鉴权失败
                .exceptionHandling().authenticationEntryPoint(jwtAuthError).accessDeniedHandler(jwtAuthError).and()
                // 下面开始设置权限
                .authorizeRequests(authorize -> authorize
                        // 请求放开
                        .antMatchers("/**").permitAll()
                        // 其他地址的访问均需验证权限
                        .anyRequest().authenticated()
                )
                // 添加 JWT 过滤器,JWT 过滤器在用户名密码认证过滤器之前
                .addFilterBefore(authFilter(), UsernamePasswordAuthenticationFilter.class)
                // 认证用户时用户信息加载配置,注入springAuthUserService
                .userDetailsService(xxxAuthUserService)
                .build();
    }

    @Bean 
    public WebSecurityCustomizer webSecurityCustomizer() { 
        return (web) -> web.ignoring().antMatchers("/css/**","/js/**","/img/**","/uploads/**","**/favicon.ico"); 
    }

    /**
     * 配置跨源访问(CORS)
     * @return
     */
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }

}  

 

 

 安全构建器HttpSecurity和WebSecurity的区别是 :

WebSecurity不仅通过HttpSecurity定义某些请求的安全控制,也通过其他方式定义其他某些请求可以忽略安全控制;
HttpSecurity仅用于定义需要安全控制的请求(当然HttpSecurity也可以指定某些请求不需要安全控制);
可以认为HttpSecurity是WebSecurity的一部分,WebSecurity是包含HttpSecurity的更大的一个概念;

注意 : 这里是从语义上讲,而不是从实现层面的表示形式上讲;

构建目标不同
WebSecurity构建目标是整个Spring Security安全过滤器FilterChainProxy,
而HttpSecurity的构建目标仅仅是FilterChainProxy中的一个SecurityFilterChain。

 

测试时配置用户:

    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withDefaultPasswordEncoder().username("user").password("123456").roles("USER").build());
        manager.createUser(User.withDefaultPasswordEncoder().username("admin").password("123456").roles("ADMIN","USER").build());
        return manager;
    }

    @Autowired
    private DataSource dataSource;
    @Bean
    public UserDetailsService userDetailsServiceJdbc(){
        UserDetails user = User.builder()
                .username("user")
                .password("{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW")
                .roles("USER")
                .build();
        UserDetails admin = User.builder()
                .username("admin")
                .password("{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW")
                .roles("USER", "ADMIN")
                .build();
        JdbcUserDetailsManager users = new JdbcUserDetailsManager(dataSource);
        users.createUser(user);
        users.createUser(admin);
        return users;
    }

 

 

 

转 : https://blog.csdn.net/qq_41340258/article/details/125138902

https://blog.csdn.net/qq_45524787/article/details/125473762

https://blog.csdn.net/qiaohao0206/article/details/125571568

https://www.4spaces.org/2160.html

 https://www.51cto.com/article/751596.html

https://blog.csdn.net/weixin_43874301/article/details/111571551 

https://blog.csdn.net/qq3031195374/article/details/128979656

 

posted @ 2023-04-27 16:38  与f  阅读(1330)  评论(0编辑  收藏  举报