SpringSecurity6.0自定义数据库登录认证详细注释与两个关键点

阅读提醒

本文是基于Springboot3.0.1和Springsecurity6.0版本,阅读时请注意。

前言

Springboot升级到3.0以后,认证与授权SpringSecurity也就升到6.0了,有些写法已经跟以前的版本不太一样了。对于老手不适合阅读本文,对你没有什么帮助,但对于新手来说还是很有指导意义。

两个关键点

1.重写安全过虑配置

新版本已经放弃了WebSeucrityConfigurerAdapter,不能再用老版本的继承方法了。新版本采用的是重写SecurityFilterChain,代码如下:

package security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
        http
                .authorizeHttpRequests((authorize)->authorize
                        .requestMatchers("/login-form","/login-process").permitAll()//无需授权即可访问的url,多个地址可以这样写。
                        .requestMatchers("/company").permitAll()//也可以写一个地址。
                        .anyRequest().authenticated())//其它页面需要授权才可以访问。
                .formLogin(form->form
                        .loginPage("/login-form")//自定义的表单,可以不用框架给的默认表单。
                        .loginProcessingUrl("/login.do")//这个地址就是摆设,给外人看的,只要跟form表单的action一致就好,真正起作用的还是UserDetailsService。
                        .permitAll()
                      
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值