Spring Security
基本概念
什么是认证
认证 :用户认证就是判断一个用户的身份是否合法的过程,用户去访问系统资源时系统要求验证用户的身份信息,身份合法方可继续访问,不合法则拒绝访问。
常见的用户身份认证方式有:用户名密码登录,二维码登录,手机短信登录,指纹认证等方式。
什么是会话
用户认证通过后,为了避免用户的每次操作都进行认证可将用户的信息保证在会话中。
会话就是系统为了保持当前用户的登录状态所提供的机制,常见的有基于session方式、基于token方式等。
-
基于session的认证方式:
它的交互流程是,用户认证成功后,在服务端生成用户相关的数据保存在session(当前会话)中,发给客户端的sesssion_id 存放到 cookie 中,这样用户客户端请求时带上 session_id 就可以验证服务器端是否存在 session 数据,以此完成用户的合法校验,当用户退出系统或session过期销毁时,客户端的
-
基于token方式:
它的交互流程是,用户认证成功后,服务端生成一个token发给客户端,客户端可以放到 cookie 或 localStorage等存储中,每次请求时带上 token,服务端收到token通过验证后即可确认用户身份。
基于session的认证方式由Servlet规范定制,服务端要存储session信息需要占用内存资源,客户端需要支持cookie;基于token的方式则一般不需要服务端存储token,并且不限制客户端的存储方式。如今移动互联网时代更多类型的客户端需要接入系统,系统多是采用前后端分离的架构进行实现,所以基于token的方式更适合。
什么是授权
授权: 授权是用户认证通过根据用户的权限来控制用户访问资源的过程,拥有资源的访问权限则正常访问,没有权限则拒绝访问。
工作原理
Spring Security所解决的问题就是安全访问控制,而安全访问控制功能其实就是对所有进入系统的请求进行拦截,校验每个请求是否能够访问它所期望的资源。根据前边知识的学习,可以通过Filter或AOP等技术来实现,SpringSecurity对Web资源的保护是靠Filter实现的,所以从这个Filter来入手,逐步深入Spring Security原理。
当初始化Spring Security时,会创建一个名为SpringSecurityFilterChain 的Servlet过滤器,类型为org.springframework.security.web.FilterChainProxy,它实现了javax.servlet.Filter,因此外部的请求会经过此类,下图是Spring Security过虑器链结构图:
FilterChainProxy是一个代理,真正起作用的是FilterChainProxy中SecurityFilterChain所包含的各个Filter,同时这些Filter作为Bean被Spring管理,它们是Spring Security核心,各有各的职责,但他们并不直接处理用户的认证,也不直接处理用户的授权,而是把它们交给了认证管理器(AuthenticationManager)和决策管理器(AccessDecisionManager)进行处理,下图是FilterChainProxy相关类的UML图示。
spring Security功能的实现主要是由一系列过滤器链相互配合完成。
介绍这几个过滤器以及作用:
- SecurityContextPersistenceFilter:这个Filter是整个拦截过程的入口和出口,会在请求开始时从配置好的
SecurityContextRepository
中获取SecurityContext
,然后把设置给SecurityContextHolde
。在请求完成后将SecurityContextHolde
持有的SecurityContext
再保存到配置好的SecurityContextRepository
,同时清除securityContextHolder
所持有的SecurityContext
; - UsernamePasswordAuthenticationFilter:用于处理来自表单提交的认证。该表单必须提供对应的用户名和密码,其内部还有登录成功或失败后进行处理的
AuthenticationSuccessHandler
和AuthenticationFailureHandler
,这些都可以根据需求做相关改变; - FilterSecurityInterceptor:是用于保护web资源的,使用
AccessDecisionManager
对当前用户进行授权访问,前面已经详细介绍过了; - ExceptionTranslationFilter:能够捕获来自
FilterChain
所有的异常,并进行处理。但是它只会处理两类异常:AuthenticationException
和AccessDeniedException
,其它的异常它会继续抛出。
认证流程
- 用户提交用户名、密码被
SecurityFilterChain
中的UsernamePasswordAuthenticationFilter
过滤器获取到,封装为请求Authentication,通常情况下是UsernamePasswordAuthenticationToken
这个实现类。 - 然后过滤器将Authentication提交至认证管理器
(AuthenticationManager)
进行认证 - 认证成功后,
AuthenticationManager
身份管理器返回一个被填充满了信息的(包括上面提到的权限信息,身份信息,细节信息,但密码通常会被移除)Authentication 实例。 SecurityContextHolder
安全上下文容器将第3步填充了信息的Authentication
,通过SecurityContextHolder.getContext().setAuthentication(…)
方法,设置到其中。可以看出AuthenticationManager
接口(认证管理器)是认证相关的核心接口,也是发起认证的出发点,它的实现类为ProviderManager
。而Spring Security支持多种认证方式,因此ProviderManager
维护着一个List<AuthenticationProvider>
列表,存放多种认证方式,最终实际的认证工作是由
AuthenticationProvider
完成的。咱们知道web表单的对应的AuthenticationProvider
实现类为DaoAuthenticationProvider
,它的内部又维护着一个UserDetailsService
负责UserDetails
的获取。最终AuthenticationProvider
将UserDetails
填充至Authentication。
认证核心组件的大体关系如下:
AuthenticationProvider
通过前面的Spring Security认证流程我们得知,认证管理器(AuthenticationManager)
委托AuthenticationProvider
完成认证工作。AuthenticationProvider
是一个接口,定义如下:
public interface AuthenticationProvider {
Authentication authenticate(Authentication authentication) throws AuthenticationException;
boolean supports(Class<?> var1);
}
authenticate()
方法定义了认证的实现过程,它的参数是一个Authentication
,里面包含了登录用户所提交的用户、密码等。而返回值也是一个Authentication
,这个Authentication
则是在认证成功后,将用户的权限及其他信息重新组装后生成。
Spring Security中维护着一个List<AuthenticationProvider>
列表,存放多种认证方式,不同的认证方式使用不同的AuthenticationProvider
。如使用用户名密码登录时,使用AuthenticationProvider1
,短信登录时使用AuthenticationProvider2
等等这样的例子很多。
每个AuthenticationProvider
需要实现supports()
方法来表明自己支持的认证方式,如我们使用表单方式认证,在提交请求时Spring Security会生成UsernamePasswordAuthenticationToken
,它是一个Authentication
,里面封装着用户提交的用户名、密码信息。而对应的,哪个AuthenticationProvider
来处理它?
我们在DaoAuthenticationProvider
的基类AbstractUserDetailsAuthenticationProvider
发现以下代码:也就是说当web表单提交用户名密码时,Spring Security由DaoAuthenticationProvider
处理。
public boolean supports(Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
也就是说当web表单提交用户名密码时,Spring Security由DaoAuthenticationProvider处理。
最后,我们来看一下Authentication(认证信息)的结构,它是一个接口,我们之前提到的UsernamePasswordAuthenticationToken
就是它的实现之一:
public interface Authentication extends Principal, Serializable {
Collection<? extends GrantedAuthority> getAuthorities();
Object getCredentials();
Object getDetails();
Object getPrincipal();
boolean isAuthenticated();
void setAuthenticated(boolean var1) throws IllegalArgumentException;
}
- Authentication是spring security包中的接口,直接继承自Principal类,而Principal是位于java.security
包中的。它是表示着一个抽象主体身份,任何主体都有一个名称,因此包含一个getName()
方法。 - getAuthorities(),权限信息列表,默认是
GrantedAuthority
接口的一些实现类,通常是代表权限信息的一系
列字符串。 - getCredentials(),凭证信息,用户输入的密码字符串,在认证过后通常会被移除,用于保障安全。
- getDetails(),细节信息,web应用中的实现接口通常为
WebAuthenticationDetails
,它记录了访问者的ip地
址和sessionId的值。 - getPrincipal(),身份信息,大部分情况下返回的是
UserDetails
接口的实现类,UserDetails
代表用户的详细
信息,那从Authentication
中取出来的UserDetails
就是当前登录用户信息,它也是框架中的常用接口之一。
UserDetailsService
咱们现在知道
DaoAuthenticationProvider
处理了web表单的认证逻辑,认证成功后既得到一个Authentication(UsernamePasswordAuthenticationToken实现)
,里面包含了身份信息(Principal)。这个身份信息就是一个Object ,大多数情况下它可以被强转为UserDetails
对象。
DaoAuthenticationProvider
中包含了一个UserDetailsService
实例,它负责根据用户名提取用户信息UserDetails
(包含密码),而后DaoAuthenticationProvider
会去对比UserDetailsService
提取的用户密码与用户提交的密码是否匹配作为认证成功的关键依据,因此可以通过将自定义的UserDetailsService
公开为spring bean来定义自定义身份验证。
public interface UserDetailsService {
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}
很多人把
DaoAuthenticationProvider
和UserDetailsService
的职责搞混淆,其实UserDetailsService
只负责从特定的地方(通常是数据库)加载用户信息,仅此而已。而DaoAuthenticationProvider
的职责更大,它完成完整的认证流程,同时会把UserDetails
填充至Authentication
。上面一直提到UserDetails
是用户信息,咱们看一下它的真面目:
public interface UserDetails extends Serializable {
Collection<? extends GrantedAuthority> getAuthorities();
String getPassword();
String getUsername();
boolean isAccountNonExpired();
boolean isAccountNonLocked();
boolean isCredentialsNonExpired();
boolean isEnabled();
}
-
它和
Authentication
接口很类似,比如它们都拥有username,authorities。 -
Authentication
的getCredentials()
与UserDetails
中的getPassword()
需要被区分对待,前者是用户提交的密码凭证,后者是用户实际存储的密码,认证其实就是对这两者的比对。 -
Authentication
中的getAuthorities()
实际是由UserDetails
的getAuthorities()
传递而形成的。Authentication
接口中的getDetails()
方法,其中的UserDetails
用户详细信息便是经过了AuthenticationProvider
认证之后被填充的。 -
通过实现
UserDetailsService
和UserDetails
,我们可以完成对用户信息获取方式以及用户信息字段的扩展。Spring Security提供的InMemoryUserDetailsManager(内存认证)
,JdbcUserDetailsManager(jdbc认证)
就是UserDetailsService
的实现类,主要区别无非就是从内存还是从数据库加载用户。
PasswordEncoder
DaoAuthenticationProvider认证处理器通过UserDetailsService获取到UserDetails后,它是如何与请求Authentication中的密码做对比呢?
在这里Spring Security为了适应多种多样的加密类型,又做了抽象,DaoAuthenticationProvider通过PasswordEncoder接口的matches方法进行密码的对比,而具体的密码对比细节取决于实现:
public interface PasswordEncoder {
String encode(CharSequence var1);
boolean matches(CharSequence var1, String var2);
default boolean upgradeEncoding(String encodedPassword) {
return false;
}
}
实际项目中推荐使用BCryptPasswordEncoder, Pbkdf2PasswordEncoder, SCryptPasswordEncoder等。而且项目中存储在数据库中的密码并不是原始密码,都是经过加密处理的密码。
授权流程
Spring Security可以通过
http.authorizeRequests()
对web请求进行授权保护。Spring Security使用标准Filter建立了对web请求的拦截,最终实现对资源的授权访问。
Spring Security的授权流程如下:
流程分析:
-
拦截请求,已认证用户访问受保护的web资源将被
SecurityFilterChain
中的FilterSecurityInterceptor
的子
类拦截。 -
获取资源访问策略,
FilterSecurityInterceptor
会从SecurityMetadataSource
的子类
DefaultFilterInvocationSecurityMetadataSource
获取要访问当前资源所需要的权限
Collection<ConfigAttribute>
。(SecurityMetadataSource
其实就是读取访问策略的抽象,而读取的内容,其实就是我们配置的访问规则, 读取访问策略) -
最后,
FilterSecurityInterceptor
会调用AccessDecisionManager
进行授权决策,若决策通过,则允许访问资源,否则将禁止访问
AccessDecisionManager(访问决策管理器)的核心接口:
public interface AccessDecisionManager {
/**
* 通过传递的参数来决定用户是否有访问对应受保护资源的权限
*/
//参数说明:
//authentication:要访问资源的访问者的身份
//object:要访问的受保护资源,web请求对应FilterInvocation
//configAttributes:是受保护资源的访问策略,通过SecurityMetadataSource获取
//decide接口就是用来鉴定当前用户是否有访问对应受保护资源的权限。
public void decide(Authentication authentication , Object object, Collection<ConfigAttribute>
configAttributes ) throws AccessDeniedException, InsufficientAuthenticationException;
//..
}
授权决策
AccessDecisionManager
采用投票的方式来确定是否能够访问受保护资源。
通过上图可以看出,AccessDecisionManager中包含的一系列AccessDecisionVoter将会被用来对Authentication是否有权访问受保护对象进行投票,AccessDecisionManager根据投票结果,做出最终决策。
AccessDecisionVoter是一个接口,其中定义有三个方法,具体结构如下所示。
//如果一个AccessDecisionVoter不能判定当前Authentication是否拥有访问对应受保护对象的权限,则其vote()方法的返回值应当为弃权ACCESS_ABSTAIN。
public interface AccessDecisionVoter<S> {
//表示同意
int ACCESS_GRANTED = 1;
//表示弃权
int ACCESS_ABSTAIN = 0;
//表示拒绝
int ACCESS_DENIED = ‐1;
boolean supports(ConfigAttribute var1);
boolean supports(Class<?> var1);
//返回结果会是AccessDecisionVoter中定义的三个常量之一,
int vote(Authentication var1, S var2, Collection<ConfigAttribute> var3);
}
Spring Security内置了三个基于投票的AccessDecisionManager
实现类如下,它们分别是AffirmativeBased
、ConsensusBased
和UnanimousBased
。
-
AffirmativeBased(Spring security默认使用的是AffirmativeBased)
只要有AccessDecisionVoter的投票为ACCESS_GRANTED则同意用户进行访问;
如果全部弃权也表示通过;
如果没有一个人投赞成票,但是有人投反对票,则将抛出AccessDeniedException。 -
ConsensusBased
如果赞成票多于反对票则表示通过。
反过来,如果反对票多于赞成票则将抛出AccessDeniedException。
如果赞成票与反对票相同且不等于0,并且属性allowIfEqualGrantedDeniedDecisions的值为true,则表示通过,否则将抛出异常AccessDeniedException。参数allowIfEqualGrantedDeniedDecisions的值默认为true。
如果所有的AccessDecisionVoter都弃权了,则将视参数allowIfAllAbstainDecisions的值而定,如果该值为true则表示通过,否则将抛出异常AccessDeniedException。参数allowIfAllAbstainDecisions的值默认为false。 -
UnanimousBased
UnanimousBased的逻辑与另外两种实现有点不一样,另外两种会一次性把受保护对象的配置属性全部传递给AccessDecisionVoter进行投票,而UnanimousBased会一次只传递一个ConfigAttribute给AccessDecisionVoter进行投票。这也就意味着如果我们的AccessDecisionVoter的逻辑是只要传递进来的ConfigAttribute中有一个能够匹配则投赞成票,但是放到UnanimousBased中其投票结果就不一定是赞成了。
UnanimousBased的逻辑具体来说是这样的:
如果受保护对象配置的某一个ConfigAttribute被任意的AccessDecisionVoter反对了,则将抛出AccessDeniedException。
如果没有反对票,但是有赞成票,则表示通过。
如果全部弃权了,则将视参数allowIfAllAbstainDecisions的值而定,true则通过,false则抛出AccessDeniedException。