spring security放行所有请求,通过配置多个WebSecurityConfigurerAdapter实现

文章介绍了在一个依赖于auth-project的main-project中,如何在开发新接口时临时跳过SpringSecurity的登录认证。提供了两种解决方案:一是自定义WebSecurity配置,通过@Order(1)确保配置优先级并禁用csrf防御;二是直接在pom.xml中注释掉auth-project的依赖。
摘要由CSDN通过智能技术生成

项目场景:

笔者最近有一个项目,依赖关系如下图:
项目依赖图

  • main-project 是主项目
  • auth-project 是公司封装好的认证中心项目,打包成了jar包供引用,基于spring security开发

需求描述

现在笔者需要在main-project上做开发,即在Controller中添加一个新接口,但是由于引用了auth-project,所以所有接口必须要先登录获取token之后才能访问。
为了便于开发,笔者想暂时跳过spring security的认证过程。

解决方案:

方法一:

在main-project的config包下编写一个类,继承WebSecurityConfigurerAdapter,并重写configure(HttpSecurity http)方法,放行所有请求,代码如下:

@EnableWebSecurity
@Order(1)
public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .anyRequest().permitAll()
                .and()
                .csrf().disable();
    }

这里有2点需要注意:

  • @Order(1)是为了配置执行顺序的优先级,因为auth-project里已经有了一个WebSecurity的配置类,所以这里配置@Order(1)是为了让我们写的配置类先加载,数字越小优先级越高;
  • 需要禁用csrf防御,否则除get请求方法以外,其它类型的请求会返回403响应。

方法二:

在main-project的pom.xml文件中,注释掉auth-project的dependency。

参考文章:

浅谈Spring @Order注解的使用
Spring Boot请求403 Forbidden错误

本文如有侵权,请联系我删除,谢谢!

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security 可以通过多个配置类来实现不同的安全策略,每个配置类都可以有自己的安全过滤器链。具体的实现方式如下: 1. 创建多个配置类,每个配置类都需要继承自 `WebSecurityConfigurerAdapter` 类。 2. 在每个配置类中覆盖 `configure(HttpSecurity http)` 方法,来实现不同的安全策略。 3. 在 `WebSecurityConfigurerAdapter` 子类中添加 `@Order(value = n)` 注解,来指定配置类的优先级,其中 n 的值越小,优先级越高。 4. 在主配置类中,使用 `@Import` 注解来导入所有的子配置类。 例如,下面是两个配置类,一个用于基于表单的身份验证,另一个用于基于 HTTP Basic 的身份验证: ```java @Configuration @Order(1) public class FormLoginWebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home") .permitAll() .and() .logout() .permitAll(); } } @Configuration @Order(2) public class HttpBasicAuthWebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/api/**").hasRole("USER") .anyRequest().authenticated() .and() .httpBasic(); } } ``` 在主配置类中,使用 `@Import` 注解来导入所有的子配置类: ```java @Configuration @EnableWebSecurity @Import({FormLoginWebSecurityConfig.class, HttpBasicAuthWebSecurityConfig.class}) public class MainWebSecurityConfig extends WebSecurityConfigurerAdapter { // ... } ``` 这样,就可以通过多个配置类来实现不同的安全策略了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值