2.spring-security认证基本原理与认证两种方式

spring-security认证基本原理与认证两种方式

在已导入的工程中添加spring-security的依赖

1
2
3
4
5
<!-- 引入spring security-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

在使用spring-security框架,该框架会默认自动替我们将系统中的资源进行保护,每次访问资源的时候都必须经过一层身份的校验,如果通过了则重定向到我们输入的URL中,否则访问是要被拒绝的,那么spring-security框架是如何实现的呢?spring security功能的实现主要是由一系列过滤器相互配合完成的,也称之为过滤器链。

 过滤器是一种典型的AOP思想,下面简单了解下这些过滤器链,后续再源码剖析中在涉及到过滤器链在仔细讲解.

org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter
根据请求封装获取WebAsyncManager,从WebAsyncManager获取/注册的安全上下文可调
用处理拦截器

org.springframework.security.web.context.SecurityContextPersistenceFilter
SecurityContextPersistenceFilter主要是使用SecurityContextRepository在session中保存
或更新一个SecurityContext,并将SecurityContext给以后的过滤器使用,来为后续fifilter
建立所需的上下文。SecurityContext中存储了当前用户的认证以及权限信息。

org.springframework.security.web.header.HeaderWriterFilter
向请求的Header中添加相应的信息,可在http标签内部使用security:headers来控制

org.springframework.security.web.csrf.CsrfFilter
csrf又称跨域请求伪造,SpringSecurity会对所有post请求验证是否包含系统生成的csrf的
token信息,如果不包含,则报错。起到防止csrf攻击的效果

org.springframework.security.web.authentication.logout.LogoutFilter
匹配URL为/logout的请求,实现用户退出,清除认证信息

org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
表单认证操作全靠这个过滤器,默认匹配URL为/login且必须为POST请求

org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter
如果没有在配置文件中指定认证页面,则由该过滤器生成一个默认认证页面

org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter
由此过滤器可以生产一个默认的退出登录页面

org.springframework.security.web.authentication.www.BasicAuthenticationFilter
此过滤器会自动解析HTTP请求中头部名字为Authentication,且以Basic开头的头信息

org.springframework.security.web.savedrequest.RequestCacheAwareFilter
通过HttpSessionRequestCache内部维护了一个RequestCache,用于缓存
HttpServletRequest

org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
针对ServletRequest进行了一次包装,使得request具有更加丰富的API

org.springframework.security.web.authentication.AnonymousAuthenticationFilter
当SecurityContextHolder中认证信息为空,则会创建一个匿名用户存入到
SecurityContextHolder中。spring security为了兼容未登录的访问,也走了一套认证流程,
只不过是一个匿名的身份

org.springframework.security.web.session.SessionManagementFilter
securityContextRepository限制同一用户开启多个会话的数量

org.springframework.security.web.access.ExceptionTranslationFilter
异常转换过滤器位于整个springSecurityFilterChain的后方,用来转换整个链路中出现的异

org.springframework.security.web.access.intercept.FilterSecurityIntercepto
获取所配置资源访问的授权信息,根据SecurityContextHolder中存储的用户信息来决定其
是否有权限

Spring Security默认加载15个过滤器, 但是随着配置可以增加或者删除一些过滤器.

 

posted @   __破  阅读(58)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示