spring Security配置拦截规则小结
作者:bug别找我
问题描述
使用spring Security实现后台管理系统登录验证加拦截,访问图片即静态资源时响应需要登录验证,分析问题得出结论未配置security的拦截规则,没有对静态资源进行登录放行
解决方案:
配置spring Security拦截规则,将访问路径添加进入白名单中,比如博主将resources下files下的图片设置白名单,规则就是"/files/**",以下就是博主的配置
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/files/**").permitAll()// 配置拦截规则 .anyRequest().authenticated(); } }
有关spring security的配置器相关规则
http.authorizeRequests().antMatchers("/api/**").denyAll(); //拒绝api路径下所有的访问 http.authorizeRequests().antMatchers("/api/**").authenticated(); //api路径下访问需认证通过 http.authorizeRequests().antMatchers("/api/**").permitAll(); //api路径下无条件允许访问
端点保护配置
了解到这部分的知识是因为在做OAuth2
认证的时候,我发现项目中的安全配置已经开放所有请求(即/**
请求不进行拦截),但是当我访问/oauth/token
的时候竟然提示401
,百思不得其解。最后发现原来在Spring Security
中预制了一些默认断点保护策略。具体配置是在AuthorizationServerSecurityConfiguration
中
过滤规则踩到的坑
.requestMatchers().antMatchers("/test/**").and() .authorizeRequests().antMatchers("/test/authenticated").authenticated() .anyRequest().permitAll().and()
通过匹配规则我们可以知道这部分配置的意思是针对/test/**
的请求将使用安全配置,/test/authenticated
是需要认证的,匹配/test/**
且不是/test/authenticated
的请求是不需要认证的。但是在实际项目中却遇到了一个坑,就是我访问/test/**
的任何请求都是需要认证的,跟了源码发现是使用错误,具体原因是因为我在继承WebSecurityConfigurerAdapter
重写configure(HttpSecurity http)
方法的最后多写了一行代码
super.configure(http);
我在最后又去调用了WebSecurityConfigurerAdapter
的configure(HttpSecurity http)
方法
protected void configure(HttpSecurity http) throws Exception { logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity)."); http .authorizeRequests().anyRequest().authenticated().and() .formLogin().and() .httpBasic(); }
这个是WebSecurityConfigurerAdapter.configure
方法的源码,它默认会对所有请求进行过滤。有兴趣的同学可以跟踪源码会发现Spring Security
对URL
拦截规则最后是存放在Map
中,即在super
的配置会覆盖掉自定义配置导致自定义配置失效,写的比较简洁可能不是很好理解。
到此这篇关于spring Security配置拦截规则小结的文章就介绍到这了,更多相关spring Security 拦截规则内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:
- SpringSecurity自定义资源拦截规则及登录界面跳转问题
- SpringSecurity拦截器链的使用详解
- springsecurity实现拦截器的使用示例
- SpringBoot整合SpringSecurity实现认证拦截的教程
- Swagger2不被SpringSecurity框架拦截的配置及说明
- Spring Boot security 默认拦截静态资源的解决方法
- SpringSecurity实现动态url拦截(基于rbac模型)
- Spring Security拦截器引起Java CORS跨域失败的问题及解决
- SpringBoot+SpringSecurity 不拦截静态资源的实现
- 浅谈Spring Security 对于静态资源的拦截与放行