栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringSecurity整体架构

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringSecurity整体架构

Security整体架构

认证

Authentication ManagerAuthenticationSecurityContexHolder 授权

AccessDecisionManagerAccessDecisionVoterConfigAttribute

在Spring Security的架构设计中,认证Authentication和授权Authorization是分开的,无论使用什么样的认证方式。都不会影响授权,这是两个独立的存在,这种独立带来的好处之一,就是可以非常方便地整合一些外部的解决方案。

认证 Authentication Manager

在Spring Security中认证是由Authentication Manager接口来负责的,接口定义为:

public interface AuthenticationManager {
    Authentication authenticate(Authentication var1) throws AuthenticationException;
}

返回Authentication表示认证成功返回Authentication Exception异常,表示认证失败。

Authentication Manager主要实现类为Provider Manager,在Provider Manager中管理了众多Authentication Provider实例。在一次完整的认证流程中,Spring Security 允许存在多个Authentication Provider ,用来实现多种认证方式,这些Authentication Provider都是由Provider Manager 进行统一管理的。

Authentication

认证以及认证成功的信息主要是由Authentication的实现类进行保存的,其接口定义为:

public interface Authentication extends Principal, Serializable {
	// 获取用户权限信息
    Collection getAuthorities();
	//获取用户凭证信息,一般指密码
    Object getCredentials();
	//获取用户详细信息
    Object getDetails();
	//获取用户身份信息,用户名、用户对象等
    Object getPrincipal();
	//用户是否认证成功
    boolean isAuthenticated();
	//设置认证标记
    void setAuthenticated(boolean var1) throws IllegalArgumentException;
}
SecurityContexHolder

SecurityContextHolderg用来获取登录之后用户信息。Spring Security会将登录用户数据保存在Session 中。但是,为了使用方便,Spring Security在此基础上还做了一些改进,其中最主要的一个变化就是线程绑定。当用户登录成功后,Spring Security 会将登录成功的用户信息保存到SecurityContextHolder中。SecurityContextHolder中的数据保存默认是通过ThreadLocal来实现的,使用ThreadLocal创建的变量只能被当前线程访问,不能被其他线程访问和修改,也就是用户数据和请求线程绑定在一起。当登录请求处理完毕后,Spring Security 会将SecurityContextHolder中的数据拿出来保存到Session中,同时将SecurityContexHolder中的数据清空。以后每当有请求到来时,Spring Security就会先从 Session中取出用户登录数据,保存到SecurityContextHolder中,方便在该请求的后续处理过程中使用,同时在请求结束时将SecurityContextHolder中的数据拿出来保存到Session中,然后将Security

SecurityContextHolder中的数据清空。这一策略非常方便用户在Controller、Service层以及任何代码中获取当前登录用户数据。

授权

当完成认证后,接下米就是授权了。在 Spring Securitl 的授权体系中,有两个关键接口,

AccessDecisionManager

AccessDecisionManager(访问决策管理器),用来决定此次访问是否被允许。

AccessDecisionVoter

AccessDecisionVoter(访问决定投票器),投票器会检查用户是否具备应有的角色,进行投出赞成、反对或者是弃权票。

AveasDecisionVoter和 AccessDecisionManager都有众多的实现类,在AccessDecisionManager中会换个遍历AccessDecisionVoter,进而决定是否允许用户访问,因而AveasDecisionVoter和AccessDecisionManager两者的关系类似于AuthenticationProvider和ProviderManager的关系。

ConfigAttribute

configAttribute,用来保存授权时的角色信息。

在Spring security中,用户请求一个资源(通常是一个接口或者一个Java方法)需要的角色会被封装成一个ConfigAttribute对象,在ConfigAttribute 中只有一个getAttribute方法,该方法返回一个Sting字符串,就是角色的名称。一般来说,角色名称都带有一个 ROLE_前缀,投票器AccessDecisionVoter所做的事情,其实就是比较用户所具各的角色和请求某个资源所需的ConfioAutihute之间的关系。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/763833.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号