spring boot security设置忽略地址不生效

最近在试下微服务改造,出现这样一个问题所有请求都经过spring cloud gateway进行认证授权后再访问后端数据方服务,但有些需要合作机构回调,由于进行了security认证,最终的方案是对回调地址进行忽略auth认证。

最终security主要代码如下:

@configuration
@enablewebsecurity
public class websecurityconfig extends websecurityconfigureradapter {
 @override
 public void configure(websecurity web) throws exception {
  web.ignoring().antmatchers("/v1/prnotifyback");
 }
 @override
 protected void configure(httpsecurity http) throws exception {
  /**表示所有的访问都必须进行认证处理后才可以正常进行*/
  http.httpbasic().and().authorizerequests().anyrequest().fullyauthenticated();
  /**所有的rest服务一定要设置为无状态,以提升操作性能*/
  http.sessionmanagement().sessioncreationpolicy(sessioncreationpolicy.stateless);
  http.csrf().disable();
 }
}

这个过程遇到了几个问题:

1、继承websecurityconfigureradapter

后我们重写configure方法,这个方法需要注意:他有两个不同的参数。

httpsecurity 及websecurity 作用是不一样的,websecurity 主要针对的全局的忽略规则,httpsecurity主要是权限控制规则。

所以一开始用httpsecurity是达不到忽略地址的目的。

 protected void configure(httpsecurity http){.......}
 public void configure(websecurity web) {.........}

websecurity

全局请求忽略规则配置(比如说静态文件,比如说注册页面)、全局httpfirewall配置、是否debug配置、全局securityfilterchain配置、privilegeevaluator、expressionhandler、securityinterceptor、

httpsecurity

具体的权限控制规则配置。

2、忽略不生效问题

web.ignoring().antmatchers("/pr/v1/prnotifyback");

如上代码如果带上/pr就不会生效,访问依然会出现401错误。/pr是配置的项目路径。但带上项目路径就不生效,这个问题很疑惑。

server:
port: 8089
servlet:
context-path: /pr

springboot springsecurity, web.ignore失效

@configuration
@enableglobalmethodsecurity(prepostenabled=true)
public class customsecurityconfig extends websecurityconfigureradapter {
    @override
    protected void configure(httpsecurity http) throws exception {
        http.sessionmanagement().sessioncreationpolicy(sessioncreationpolicy.stateless).and()
                .csrf().disable()
                .authorizerequests()
                .antmatchers("/api/**").authenticated()
                .and()
                .addfilterbefore(new tokenfilter(), usernamepasswordauthenticationfilter.class);
    }
    @override
    public void configure(websecurity web) throws exception {
        web.ignoring()
                .antmatchers("/")
                .antmatchers("/swagger-ui.html")
                .antmatchers("/swagger-resources/**")
                .antmatchers("/webjars/springfox-swagger-ui/**")
                .antmatchers("/v2/api-docs/**");
    }
}

这是修改后正常工作的配置文件

之前使用@component注解, 然后使用@resource注入进来.

导致过滤器全局生效.

正常配置,应该手动new, 而且过滤器类不能加@component注解

具体原因,之后有空研究一下.

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。