Spring Security6.x的登录验证

版本为:SpringBoot3.1.2, Spring Security 6.1.2

       博主学习三更博客项目的时候,在P35中遇到一个问题,在Spring Security6版本中,很多类被废弃,而且有些方法的名字和用法也已经更改,所以通过查询很多资料,将需要的更改总结如下:
1 更改SecurityConfig.java文件

@Configuration
//添加security过滤器
@EnableWebSecurity
public class SecurityConfig{

    @Resource
    UserDetailsServiceImpl userDetailsService;

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // 基于 token,不需要 csrf
                // csrf表示跨域漏洞防御
                // 可以使用Customizer.withDefaults():关闭
                // 相当于csrf -> csrf.disable()
                .csrf(csrf -> csrf.disable())
                // 基于 token,不需要 session
                .sessionManagement(withDefaults());
        // 设置 处理认证失败、鉴权失败处理器
        http.exceptionHandling(withDefaults());
        http
                // authorizeHttpRequests:针对http请求进行授权配置
                // permitAll: 具有所有权限,也就是可以匿名访问
                // authenticated: 认证【登录】
                .authorizeHttpRequests(authorizeHttpRequests ->
                        authorizeHttpRequests
                        .requestMatchers("/login").anonymous()
                        // 其他地址的访问均需验证权限
                        .anyRequest().permitAll()
                );
               // 添加认证过滤器,过滤器在用户名密码认证过滤器之前
                //.addFilterBefore(new JwtFilter(), UsernamePasswordAuthenticationFilter.class)
                // 退出
                //.logout(logout -> logout.disable());
                //允许跨域
        return http.cors(withDefaults()).build();
    }

    @Bean
    // 密码加密,方便之后进行密码加密对比
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception{
        return config.getAuthenticationManager();
    }

    @Bean
    public AuthenticationProvider authenticationProvider(){
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        return daoAuthenticationProvider;
    }

}

2 如果后续运行出现java.lang.ClassNotFoundException:javax.xml.bind.DatatypeConverter
需要在framework中的pom.xml中添加依赖

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>

参考链接:

https://blog.csdn.net/weixin_43883917/article/details/124430507

https://blog.csdn.net/hsuehgw/article/details/129140646

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值