SpringSecurity配置多个HttpSecurity

一、创建项目并导入依赖

   

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-security</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

   

   

二、相关配置和代码

   

查看这篇博客有相关介绍https://www.cnblogs.com/fernfei/p/12185186.html

   

1)创建一个MultiSecurityConfig配置类

   

注:在MultiSecurityConfig类上加上@configuration注解

   

2)在方法上注入,好让多个httpsecurity共用一个账户密码

   

@Bean和@Component都是把类注册成spring组件,那为什么要有两个?

   

如果你想要将第三方库中的组件装配到你的应用中,在这种情况下,是没有办法在它的类上添加@Component注解的,因此就不能使用自动化装配的方案了,但是我们可以使用@Bean

   

   

3)在MultiSecurityConfig配置类中创建两个内部类

   

分别是AdminSecurityConfig和OtherSecurityConfig内部类

   

3.1)在AdminSecurityConfig类上加@order(1)表示该类优先级高于OtherSecurityConfig

   

注:@order()中的数字越小,优先级越高

   

   

   

截图里面的具体代码可以翻我上面链接的另一个文章

   

我解释一下我理解我注释那部分,为什么不那样写

   

如果使用在AdminSecurityConfig中http.authorizeRequest(),会和OtherSecurityConfig中的http.authorizeRequest()重复,从而导致springboot以为这是两个授权的请求路径导致无法访问登陆处理接口

   

   

剩下的配置都和单个HttpSecurity一模一样可以直接访问这篇博客https://www.cnblogs.com/fernfei/p/12185186.html

   

原文地址:https://www.cnblogs.com/fernfei/p/12189589.html