本文主要聊一下spring security的permitAll以及webIgnore的区别

permitAll配置实例

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/css/**", "/js/**","/fonts/**").permitAll().anyRequest().authenticated();}
}复制代码

web ignore配置实例

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overridepublic void configure(WebSecurity web) throws Exception {web.ignoring().antMatchers("/css/**");web.ignoring().antMatchers("/js/**");web.ignoring().antMatchers("/fonts/**");}
}复制代码

二者区别

顾名思义,WebSecurity主要是配置跟web资源相关的,比如css、js、images等等,但是这个还不是本质的区别,关键的区别如下:

  • ingore是完全绕过了spring security的所有filter,相当于不走spring security
  • permitall没有绕过spring security,其中包含了登录的以及匿名的。

AnonymousAuthenticationFilter

spring-security-web-4.2.3.RELEASE-sources.jar!/org/springframework/security/web/authentication/AnonymousAuthenticationFilter.java

/*** Detects if there is no {@code Authentication} object in the* {@code SecurityContextHolder}, and populates it with one if needed.** @author Ben Alex* @author Luke Taylor*/
public class AnonymousAuthenticationFilter extends GenericFilterBean implementsInitializingBean {//......public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)throws IOException, ServletException {if (SecurityContextHolder.getContext().getAuthentication() == null) {SecurityContextHolder.getContext().setAuthentication(createAuthentication((HttpServletRequest) req));if (logger.isDebugEnabled()) {logger.debug("Populated SecurityContextHolder with anonymous token: '"+ SecurityContextHolder.getContext().getAuthentication() + "'");}}else {if (logger.isDebugEnabled()) {logger.debug("SecurityContextHolder not populated with anonymous token, as it already contained: '"+ SecurityContextHolder.getContext().getAuthentication() + "'");}}chain.doFilter(req, res);}protected Authentication createAuthentication(HttpServletRequest request) {AnonymousAuthenticationToken auth = new AnonymousAuthenticationToken(key,principal, authorities);auth.setDetails(authenticationDetailsSource.buildDetails(request));return auth;}//......
}复制代码

这个filter的主要功能就是给没有登陆的用户,填充AnonymousAuthenticationToken到SecurityContextHolder的Authentication,后续依赖Authentication的代码可以统一处理。

FilterComparator

spring-security-config-4.1.4.RELEASE-sources.jar!/org/springframework/security/config/annotation/web/builders/FilterComparator.java

final class FilterComparator implements Comparator<Filter>, Serializable {private static final int STEP = 100;private Map<String, Integer> filterToOrder = new HashMap<String, Integer>();FilterComparator() {int order = 100;put(ChannelProcessingFilter.class, order);order += STEP;put(ConcurrentSessionFilter.class, order);order += STEP;put(WebAsyncManagerIntegrationFilter.class, order);order += STEP;put(SecurityContextPersistenceFilter.class, order);order += STEP;put(HeaderWriterFilter.class, order);order += STEP;put(CorsFilter.class, order);order += STEP;put(CsrfFilter.class, order);order += STEP;put(LogoutFilter.class, order);order += STEP;put(X509AuthenticationFilter.class, order);order += STEP;put(AbstractPreAuthenticatedProcessingFilter.class, order);order += STEP;filterToOrder.put("org.springframework.security.cas.web.CasAuthenticationFilter",order);order += STEP;put(UsernamePasswordAuthenticationFilter.class, order);order += STEP;put(ConcurrentSessionFilter.class, order);order += STEP;filterToOrder.put("org.springframework.security.openid.OpenIDAuthenticationFilter", order);order += STEP;put(DefaultLoginPageGeneratingFilter.class, order);order += STEP;put(ConcurrentSessionFilter.class, order);order += STEP;put(DigestAuthenticationFilter.class, order);order += STEP;put(BasicAuthenticationFilter.class, order);order += STEP;put(RequestCacheAwareFilter.class, order);order += STEP;put(SecurityContextHolderAwareRequestFilter.class, order);order += STEP;put(JaasApiIntegrationFilter.class, order);order += STEP;put(RememberMeAuthenticationFilter.class, order);order += STEP;put(AnonymousAuthenticationFilter.class, order);order += STEP;put(SessionManagementFilter.class, order);order += STEP;put(ExceptionTranslationFilter.class, order);order += STEP;put(FilterSecurityInterceptor.class, order);order += STEP;put(SwitchUserFilter.class, order);}//......
}复制代码

这个类定义了spring security内置的filter的优先级,AnonymousAuthenticationFilter在倒数第五个执行,在FilterSecurityInterceptor这个类之前。

FilterSecurityInterceptor

spring-security-web-4.2.3.RELEASE-sources.jar!/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.java

/*** Performs security handling of HTTP resources via a filter implementation.* <p>* The <code>SecurityMetadataSource</code> required by this security interceptor is of* type {@link FilterInvocationSecurityMetadataSource}.* <p>* Refer to {@link AbstractSecurityInterceptor} for details on the workflow.* </p>** @author Ben Alex* @author Rob Winch*/
public class FilterSecurityInterceptor extends AbstractSecurityInterceptor implementsFilter {//......
}复制代码

这个相当于spring security的核心处理类了,它继承抽象类AbstractSecurityInterceptor

spring-security-core-4.2.3.RELEASE-sources.jar!/org/springframework/security/access/intercept/AbstractSecurityInterceptor.java

public abstract class AbstractSecurityInterceptor implements InitializingBean,ApplicationEventPublisherAware, MessageSourceAware {//......protected InterceptorStatusToken beforeInvocation(Object object) {Assert.notNull(object, "Object was null");final boolean debug = logger.isDebugEnabled();if (!getSecureObjectClass().isAssignableFrom(object.getClass())) {throw new IllegalArgumentException("Security invocation attempted for object "+ object.getClass().getName()+ " but AbstractSecurityInterceptor only configured to support secure objects of type: "+ getSecureObjectClass());}Collection<ConfigAttribute> attributes = this.obtainSecurityMetadataSource().getAttributes(object);if (attributes == null || attributes.isEmpty()) {if (rejectPublicInvocations) {throw new IllegalArgumentException("Secure object invocation "+ object+ " was denied as public invocations are not allowed via this interceptor. "+ "This indicates a configuration error because the "+ "rejectPublicInvocations property is set to 'true'");}if (debug) {logger.debug("Public object - authentication not attempted");}publishEvent(new PublicInvocationEvent(object));return null; // no further work post-invocation}if (debug) {logger.debug("Secure object: " + object + "; Attributes: " + attributes);}if (SecurityContextHolder.getContext().getAuthentication() == null) {credentialsNotFound(messages.getMessage("AbstractSecurityInterceptor.authenticationNotFound","An Authentication object was not found in the SecurityContext"),object, attributes);}Authentication authenticated = authenticateIfRequired();// Attempt authorizationtry {this.accessDecisionManager.decide(authenticated, object, attributes);}catch (AccessDeniedException accessDeniedException) {publishEvent(new AuthorizationFailureEvent(object, attributes, authenticated,accessDeniedException));throw accessDeniedException;}if (debug) {logger.debug("Authorization successful");}if (publishAuthorizationSuccess) {publishEvent(new AuthorizedEvent(object, attributes, authenticated));}// Attempt to run as a different userAuthentication runAs = this.runAsManager.buildRunAs(authenticated, object,attributes);if (runAs == null) {if (debug) {logger.debug("RunAsManager did not change Authentication object");}// no further work post-invocationreturn new InterceptorStatusToken(SecurityContextHolder.getContext(), false,attributes, object);}else {if (debug) {logger.debug("Switching to RunAs Authentication: " + runAs);}SecurityContext origCtx = SecurityContextHolder.getContext();SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());SecurityContextHolder.getContext().setAuthentication(runAs);// need to revert to token.Authenticated post-invocationreturn new InterceptorStatusToken(origCtx, true, attributes, object);}}//......
}复制代码

主要的逻辑在这个beforeInvocation方法,它就依赖了authentication

private Authentication authenticateIfRequired() {Authentication authentication = SecurityContextHolder.getContext().getAuthentication();if (authentication.isAuthenticated() && !alwaysReauthenticate) {if (logger.isDebugEnabled()) {logger.debug("Previously Authenticated: " + authentication);}return authentication;}authentication = authenticationManager.authenticate(authentication);// We don't authenticated.setAuthentication(true), because each provider should do// thatif (logger.isDebugEnabled()) {logger.debug("Successfully Authenticated: " + authentication);}SecurityContextHolder.getContext().setAuthentication(authentication);return authentication;}复制代码

这个方法判断authentication如果是已经校验过的,则返回;没有校验过的话,则调用authenticationManager进行鉴权。

而AnonymousAuthenticationFilter设置的authentication在这个时候就派上用场了
spring-security-core-4.2.3.RELEASE-sources.jar!/org/springframework/security/authentication/AnonymousAuthenticationToken.java
```
public class AnonymousAuthenticationToken extends AbstractAuthenticationToken implements
Serializable {
private AnonymousAuthenticationToken(Integer keyHash, Object principal,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);

    if (principal == null || "".equals(principal)) {throw new IllegalArgumentException("principal cannot be null or empty");}Assert.notEmpty(authorities, "authorities cannot be null or empty");this.keyHash = keyHash;this.principal = principal;setAuthenticated(true);
}
//......复制代码

}
```

它默认就是authenticated

小结

  • web ignore比较适合配置前端相关的静态资源,它是完全绕过spring security的所有filter的;
  • 而permitAll,会给没有登录的用户适配一个AnonymousAuthenticationToken,设置到SecurityContextHolder,方便后面的filter可以统一处理authentication。

doc

  • spring security 的几个细节
  • Spring Security – security none, filters none, access permitAll
  • Spring Security permitAll() not allowing anonymous access
  • Difference between access=“permitAll” and filters=“none”?

聊聊spring security的permitAll以及webIgnore相关推荐

  1. 理解Spring Security中permitAll()和anonymous()的区别

    从 Spring文档: 采用"默认拒绝"通常被认为是良好的安全实践,您可以明确指定允许的内容并禁止其他所有内容.定义未经身份验证的用户可以访问的内容是类似的情况,尤其是对于 Web ...

  2. spring security自定义指南

    序 本文主要研究一下几种自定义spring security的方式 主要方式 自定义UserDetailsService 自定义passwordEncoder 自定义filter 自定义Authent ...

  3. Spring Security 中,想在权限中使用通配符,怎么做?

    小伙伴们知道,在 Shiro 中,默认是支持权限通配符的,例如系统用户有如下一些权限: system:user:add system:user:delete system:user:select sy ...

  4. You are asking Spring Security to ignore Ant(xx) This is not recommended, please use permitAll... 处理

    Spring Security之ignore not recommended 警告的处理 启动springboot项目时,出现一个warning: You are asking Spring Secu ...

  5. Spring Security – security none, filters none, access permitAll

    1.概述 Spring Security提供了几种将请求模式配置为不安全或允许所有访问的机制.取决于这些机制中的哪一种 - 这可能意味着根本不在该路径上运行安全过滤器链,或者运行过滤器链并允许访问 2 ...

  6. Spring Security 实战干货:实现自定义退出登录

    点击上方蓝色"程序猿DD",选择"设为星标" 回复"资源"获取独家整理的学习资料! 1. 前言 上一篇对 Spring Security 所 ...

  7. spring boot整合spring security笔记

    最近自己做了一个小项目,正在进行springboot和spring Security的整合,有一丢丢的感悟,在这里分享一下: 首先,spring boot整合spring security最好是使用T ...

  8. Spring Security 之集群Session配置

    1.   新建Maven项目 cluster-session 2.   pom.xml <project xmlns="http://maven.apache.org/POM/4.0. ...

  9. 聊聊Spring Boot服务监控,健康检查,线程信息,JVM堆信息,指标收集,运行情况监控等!...

    来自:https://juejin.im/post/5e2179def265da3e152d2561 前言 去年我们项目做了微服务1.0的架构转型,但是服务监控这块却没有跟上.这不,最近我就被分配了要 ...

最新文章

  1. 2021年大数据Flink(三十四):​​​​​​​Table与SQL ​​​​​​案例一
  2. Nature子刊:加州大学伯克利分校Banfield组发现某些淡水湖泊中的大噬菌体或能加速好氧甲烷氧化...
  3. EJB(四)JPA 分布式事务处理
  4. 寒哥细谈之AutoLayout全解
  5. python读取扫描形成的pdf_Python利用PyPDF2库获取PDF文件总页码实例
  6. IE8兼容问题总结---trim()方法
  7. java base64 转图片不现实_Base64.decodeBase64将base64转图片的问题
  8. C++ 在程序中设置环境变量
  9. 快速远程访问内网的摄像头【内网穿透】
  10. 视频2-视频文件解析和格式说明
  11. Telemetry 基础
  12. 密码学实验4 欧拉数求解和DES的初始置换
  13. java计算机毕业设计淮安城市开放大学实习实训管理系统源码+mysql数据库+系统+lw文档+部署
  14. java面向对象三大特性之多态---编译时多态和运行时多态详解
  15. 星星之火-55:什么是微观量子?什么是量子的六大特征?什么是微观量子通信?
  16. 微信公众号获取微信用户共享收货地址
  17. HTML首字下沉的编码,CSS_有关首行首字下沉的实现原理及代码,下面是两个个小技巧,一个是 - phpStudy...
  18. 以下c语言程序片段用于估测cpu的cache参数,阿里巴巴笔试题
  19. macOS如何正确驱动集成显卡HDMI(包括视频和音频)
  20. 使用阿里云dns+oss+cdn+ssl发布静态网站

热门文章

  1. 小学计算机课知识点总结,小学计算机教学总结3篇
  2. php 使用sendgrid api 发送邮件_linux - 使用命令发送邮件
  3. powerdesigner 概念模型_“使用满足”分析框架下社交媒体用户持续使用行为的概念模型研究...
  4. mysql workbench crows foot_佳句赏析“英文人生名言:1、A road of a thousand ...先洗浄你的手指,再指出我的污迹。” - 金句吧...
  5. 【阿里云课程】模型设计之动态网络,原理与设计
  6. 全球及中国医养结合产业发展战略建议与投资价值评估报告2022版
  7. 全球及中国智能照明行业应用状况及竞争格局展望报告2021-2027年
  8. batchnorm2d参数 torch_Pytorch-nn.BatchNorm2d()
  9. 安义县农业结构调整-农业大健康·林裕豪:从玉农业谋定基地
  10. SD:配置国家代码的检查和客户主数据隐藏字段 20190516