- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
Spring Security 核心类简介
Spring Security 核⼼类简介
核⼼类简介
Authentication
Authentication 是⼀个接⼜,⽤来表⽰⽤户认证信息的,在⽤户登录认证之前相关信息
会封装为⼀个 Authentication 具体实现 的对象,在登录认证成功之后又会⽣成⼀个
信息更全⾯,包含⽤户权限等信息的 Authentication 对象,然后把它保存在
SecurityContextHolder 所持有的 SecurityContext 中,供后续的程序进⾏调⽤,如访问
权限的鉴定等。
SecurityContextHolder
SecurityContextHolder 是⽤来保存 SecurityContext 的。SecurityContext 中含有当前正在
访问系统的⽤户的详细信息。默认情况下,SecurityContextHolder 将使⽤ ThreadLocal
来保存 SecurityContext ,这也就意味着在处于同⼀线程中的⽅法中我们可以从
ThreadLocal 中获取到当前的 SecurityContext 。因为线程池的原因,如果我们每次在请
求完成后都将 ThreadLocal 进⾏清除的话,那么我们把 SecurityContext 存放在
ThreadLocal 中还是⽐较安全的。这些⼯作 Spring Security 已经⾃动为我们做了,即在
每⼀次 request 结束后都将清除当前线程的 ThreadLocal 。
SecurityContextHolder 中定义了⼀系列的静态⽅法,⽽这些静态⽅法内部逻辑基本上
都是通过 SecurityContextHolder 持有的 SecurityContextHolderStrategy 来实现的,如
getContext()、setContext()、clearContext()等。⽽默认使⽤的 strategy 就是基于
ThreadLocal 的 ThreadLocalSecurityContextHolderStrategy 。另外,Spring Security 还提
供了两种 型的 strategy 实现,GlobalSecurityContextHolderStrategy 和
InheritableThreadLocalSecurityContextHolderStrategy ,前者表⽰全局使⽤同⼀个
SecurityContext ,如 C/S 结构的客户端;后者使⽤ InheritableThreadLocal 来存放
SecurityContext ,即⼦线程可以使⽤⽗线程中存放的变量。
⼀般⽽⾔,我们使⽤默认的 strategy 就可以了,但是如果要改变默认的 strategy ,
Spring Security 为我们提供了两种⽅法,这两种⽅式都是通过改变 strategy ame 来实
现的。SecurityContextHolder 中为三种不同 型的 strategy 分别命名为
MODE_THREADLOCAL 、MODE_I HERITABLETHREADLOCAL 和
MODE_GLOBAL 。第⼀种⽅式是通过 SecurityContextHolder 的静态⽅法
setStrategy ame() 来指定需要使⽤的 strategy ;第⼆种⽅式是通过系统属性进⾏指定,
其中属性名默认为 “spring .security .strategy” ,属性值为对应 strategy 的名称。
Spring Security 使⽤⼀个 Authentication 对象来描述当前⽤户的相关信息。
SecurityContextHolder 中持有的是当前⽤户的 SecurityContext ,⽽ SecurityContext 持有
的是代表当前⽤户相关信息的 Authentication 的引⽤。这个 Authentication 对象不需要
我们⾃⼰去创建,在与系统交互的过程中,Spring Security 会⾃动为我们创建相应的
Authentication 对象,然后赋值给当前的 SecurityContext 。但是往往我们需要在程序中
获取当前⽤户的相关信息,⽐如最常见的是获取当前登录⽤户的⽤户名。在程序的任
何地⽅,通过如下⽅式我们可以获取到当前⽤户的⽤户名。
public String getCurrentUsername() {
Object principa
文档评论(0)