自定义认证
2023/3/29
自定义认证
自定义资源权限
- 公共资源: 可以直接访问
- 受保护资源: 需要权限管理(认证授权之后才能访问),默认所有资源都是受保护的,需要认证授权之后才能访问
注意
- permitAll() 代表放行该资源,该资源为公共资源,无需认证和授权可以直接访问
- anyRequest().authenticated() 代表所有请求,必须认证之后才能访问
- formLogin() 代表开启表单认证
注意: 放行资源必须放在所有认证请求之前!
当系统中不存在WebSecurityConfigurerAdapter和SecurityFilterChain实例时,Spring Security会使用默认的配置。
当存在其中任何一个时,默认的配置就会失效。
Spring Security 2.6.2及以前版本
写法一:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 开启认证
.authorizeHttpRequests()
// 对于部分请求方形
.mvcMatchers("/order/test1","/order/test2","/hello/test2","/hello/test3").permitAll()
// 其余请求全部需要认证
.anyRequest().authenticated()
// 链式编程写法
.and()
// 表单登录
.formLogin();
}
}写法二:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 开启认证
.authorizeHttpRequests()
// 对于部分请求方形
.mvcMatchers("/order/test1").permitAll()
.mvcMatchers("/order/test2").permitAll()
.mvcMatchers("/hello/test2").permitAll()
.mvcMatchers("/hello/test3").permitAll()
// 其余请求全部需要认证
.anyRequest().authenticated();
// 表单登录
http.formLogin();
}
}新版Security
在SpringBoot 2.7.1 中的spring-security-config-5.7.2.RELEASE中已提到WebSecurityConfigurerAdapter已过时被弃用,替代方法如下:
使用 SecurityFilterChain Bean 来配置 HttpSecurity;
使用 WebSecurityCustomizer Bean 来配置 WebSecurity。
参考链接:
SpringSecurity - WebSecurityConfigurerAdapter 过时问题_爱上云原生的博客-CSDN博客
Spring Security即将弃用配置类WebSecurityConfigurerAdapter_码农小胖哥的博客-CSDN博客
替代后新代码为:
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.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity //添加security过滤器,此处一定要加入此注解,否则下面的httpSecurity无法装配
public class WebSecurityConfig {
/**
* 说明: SpringBoot2.7.1版本
*/
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.authorizeHttpRequests()
.mvcMatchers("/index").permitAll()
.anyRequest().authenticated()
.and().formLogin().and().build();
}
}