想要深入spring security的authentication (身份验证)和access-control(访问权限控制)工作流程,必须清楚spring security的主要技术点包括关键接口、类以及抽象类如何协同工作进行authentication 和access-control的实现。

1.spring security 认证和授权流程

常见认证和授权流程可以分成:

  1. A user is prompted to log in with a username and password (用户用账密码登录)
  2. The system (successfully) verifies that the password is correct for the username(校验密码正确性)
  3. The context information for that user is obtained (their list of roles and so on).(获取用户信息context,如权限)
  4. A security context is established for the user(为用户创建security context)
  5. The user proceeds, potentially to perform some operation which is potentially protected by an access control mechanism which checks the required permissions for the operation against the current security context information.(访问权限控制,是否具有访问权限)

1.1 spring security 认证

上述前三点为spring security认证验证环节:

  1. 通常通过AbstractAuthenticationProcessingFilter过滤器将账号密码组装成Authentication实现类UsernamePasswordAuthenticationToken;
  2. 将token传递给AuthenticationManager验证是否有效,而AuthenticationManager通常使用ProviderManager实现类来检验;
  3. AuthenticationManager认证成功后将返回一个拥有详细信息的Authentication object(包括权限信息,身份信息,细节信息,但密码通常会被移除);
  4. 通过SecurityContextHolder.getContext().getAuthentication().getPrincipal()将Authentication设置到security context中。

1.2 spring security访问授权

  1. 通过FilterSecurityInterceptor过滤器入口进入;
  2. FilterSecurityInterceptor通过其继承的抽象类的AbstractSecurityInterceptor.beforeInvocation(Object object)方法进行访问授权,其中涉及了类AuthenticationManager、AccessDecisionManager、SecurityMetadataSource等。

根据上述描述的过程,我们接下来主要去分析其中涉及的一下Component、Service、Filter。

2.核心组件(Core Component )

2.1 SecurityContextHolder

  SecurityContextHolder提供对SecurityContext的访问,存储security context(用户信息、角色权限等),而且其具有下列储存策略即工作模式:

  1. SecurityContextHolder.MODE_THREADLOCAL(默认):使用ThreadLocal,信息可供此线程下的所有的方法使用,一种与线程绑定的策略,此天然很适合Servlet Web应用。

  2. SecurityContextHolder.MODE_GLOBAL:使用于独立应用

  3. SecurityContextHolder.MODE_INHERITABLETHREADLOCAL:具有相同安全标示的线程

修改SecurityContextHolder的工作模式有两种方法 :

  1. 设置一个系统属性(system.properties) : spring.security.strategy;
  2. 调用SecurityContextHolder静态方法setStrategyName()

在默认ThreadLocal策略中,SecurityContextHolder为静态方法获取用户信息为:

  Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();if (principal instanceof UserDetails) {      String username = ((UserDetails)principal).getUsername();} else {String username = principal.toString();}
复制代码

但是一般不需要自身去获取。 其中getAuthentication()返回一个Authentication认证主体,接下来分析Authentication、UserDetails细节。

2.2 Authentication

  Spring Security使用一个Authentication对象来描述当前用户的相关信息,其包含用户拥有的权限信息列表、用户细节信息(身份信息、认证信息)。Authentication为认证主体在spring security中时最高级别身份/认证的抽象,常见的实现类UsernamePasswordAuthenticationToken。Authentication接口源码:

public interface Authentication extends Principal, Serializable { //权限信息列表,默认GrantedAuthority接口的一些实现类Collection<? extends GrantedAuthority> getAuthorities(); //密码信息Object getCredentials();//细节信息,web应用中的实现接口通常为 WebAuthenticationDetails,它记录了访问者的ip地址和sessionId的值Object getDetails();//通常返回值为UserDetails实现类Object getPrincipal();boolean isAuthenticated();void setAuthenticated(boolean var1) throws IllegalArgumentException;
}
复制代码

前面两个组件都涉及了UserDetails,以及GrantedAuthority其到底是什么呢?2.3小节分析。

2.3 UserDetails&GrantedAuthority

  UserDetails提供从应用程序的DAO或其他安全数据源构建Authentication对象所需的信息,包含GrantedAuthority。其官方实现类为User,开发者可以实现其接口自定义UserDetails实现类。其接口源码:

 public interface UserDetails extends Serializable {Collection<? extends GrantedAuthority> getAuthorities();String getPassword();String getUsername();boolean isAccountNonExpired();boolean isAccountNonLocked();boolean isCredentialsNonExpired();boolean isEnabled();
}
复制代码

  UserDetails与Authentication接口功能类似,其实含义即是Authentication为用户提交的认证凭证(账号密码),UserDetails为系统中用户正确认证凭证,在UserDetailsService中的loadUserByUsername方法获取正确的认证凭证。   其中在getAuthorities()方法中获取到GrantedAuthority列表是代表用户访问应用程序权限范围,此类权限通常是“role(角色)”,例如ROLE_ADMINISTRATOR或ROLE_HR_SUPERVISOR。GrantedAuthority接口常见的实现类SimpleGrantedAuthority。

3. 核心服务类(Core Services)

3.1 AuthenticationManager、ProviderManager以及AuthenticationProvider

  AuthenticationManager是认证相关的核心接口,是认证一切的起点。但常见的认证流程都是AuthenticationManager实现类ProviderManager处理,而且ProviderManager实现类基于委托者模式维护AuthenticationProvider 列表用于不同的认证方式。例如:

  1. 使用账号密码认证方式DaoAuthenticationProvider实现类(继承了AbstractUserDetailsAuthenticationProvide抽象类),其为默认认证方式,进行数据库库获取认证数据信息。
  2. 游客身份登录认证方式AnonymousAuthenticationProvider实现类
  3. 从cookies获取认证方式RememberMeAuthenticationProvider实现类

  AuthenticationProvider为

ProviderManager源码分析:

public Authentication authenticate(Authentication authentication)throws AuthenticationException {Class<? extends Authentication> toTest = authentication.getClass();AuthenticationException lastException = null;Authentication result = null;//AuthenticationProvider列表依次认证for (AuthenticationProvider provider : getProviders()) {if (!provider.supports(toTest)) {continue;}try {//每个AuthenticationProvider进行认证result = provider.authenticate(authentication)if (result != null) {copyDetails(authentication, result);break;}}....catch (AuthenticationException e) {lastException = e;}}//进行父类AuthenticationProvider进行认证if (result == null && parent != null) {// Allow the parent to try.try {result = parent.authenticate(authentication);}catch (AuthenticationException e) {lastException = e;}}// 如果有Authentication信息,则直接返回if (result != null) {if (eraseCredentialsAfterAuthentication&& (result instanceof CredentialsContainer)) {//清除密码((CredentialsContainer) result).eraseCredentials();}//发布登录成功事件eventPublisher.publishAuthenticationSuccess(result);return result;}//如果都没认证成功,抛出异常if (lastException == null) {lastException = new ProviderNotFoundException(messages.getMessage("ProviderManager.providerNotFound",new Object[] { toTest.getName() },"No AuthenticationProvider found for {0}"));}prepareException(lastException, authentication);throw lastException;}
复制代码

  ProviderManager 中的AuthenticationProvider列表,会依照次序去认证,默认策略下,只需要通过一个AuthenticationProvider的认证,即可被认为是登录成功,而且AuthenticationProvider认证成功后返回一个Authentication实体,并为了安全会进行清除密码。如果所有认证器都无法认证成功,则ProviderManager 会抛出一个ProviderNotFoundException异常。

3.2 UserDetailsService

  UserDetailsService接口作用是从特定的地方获取认证的数据源(账号、密码)。如何获取到系统中正确的认证凭证,通过loadUserByUsername(String username)获取认证信息,而且其只有一个方法:

UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
复制代码

其常见的实现类从数据获取的JdbcDaoImpl实现类,从内存中获取的InMemoryUserDetailsManager实现类,不过我们可以实现其接口自定义UserDetailsService实现类,如下:

public class CustomUserService implements UserDetailsService {@Autowired//用户mapperprivate UserInfoMapper userInfoMapper;@Autowired//用户权限mapperprivate PermissionInfoMapper permissionInfoMapper;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {UserInfoDTO userInfo = userInfoMapper.getUserInfoByUserName(username);if (userInfo != null) {List<PermissionInfoDTO> permissionInfoDTOS = permissionInfoMapper.findByAdminUserId(userInfo.getId());List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();//组装权限GrantedAuthority objectfor (PermissionInfoDTO permissionInfoDTO : permissionInfoDTOS) {if (permissionInfoDTO != null && permissionInfoDTO.getPermissionName() != null) {GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permissionInfoDTO.getPermissionName());grantedAuthorityList.add(grantedAuthority);}}//返回用户信息return new User(userInfo.getUserName(), userInfo.getPasswaord(), grantedAuthorityList);}else {//抛出用户不存在异常throw new UsernameNotFoundException("admin" + username + "do not exist");}}
}
复制代码

3.3 AccessDecisionManager&SecurityMetadataSource

  AccessDecisionManager是由AbstractSecurityInterceptor调用,负责做出最终的访问控制决策。

AccessDecisionManager接口源码:

 //访问控制决策void decide(Authentication authentication, Object secureObject,Collection<ConfigAttribute> attrs) throws AccessDeniedException;//是否支持处理传递的ConfigAttributeboolean supports(ConfigAttribute attribute);//确认class是否为AccessDecisionManagerboolean supports(Class clazz);
复制代码

  SecurityMetadataSource包含着AbstractSecurityInterceptor访问授权所需的元数据(动态url、动态授权所需的数据),在AbstractSecurityInterceptor授权模块中结合AccessDecisionManager进行访问授权。其涉及了ConfigAttribute。 SecurityMetadataSource接口:

Collection<ConfigAttribute> getAttributes(Object object)throws IllegalArgumentException;Collection<ConfigAttribute> getAllConfigAttributes();boolean supports(Class<?> clazz);
复制代码

我们还可以自定义SecurityMetadataSource数据源,实现接口FilterInvocationSecurityMetadataSource。例:

public class MyFilterSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {public List<ConfigAttribute> getAttributes(Object object) {FilterInvocation fi = (FilterInvocation) object;String url = fi.getRequestUrl();String httpMethod = fi.getRequest().getMethod();List<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>();// Lookup your database (or other source) using this information and populate the// list of attributesreturn attributes;}public Collection<ConfigAttribute> getAllConfigAttributes() {return null;}public boolean supports(Class<?> clazz) {return FilterInvocation.class.isAssignableFrom(clazz);}
}
复制代码

3.4 PasswordEncoder

  为了存储安全,一般要对密码进行算法加密,而spring security提供了加密PasswordEncoder接口。其实现类有使用BCrypt hash算法实现的BCryptPasswordEncoder,SCrypt hashing 算法实现的SCryptPasswordEncoder实现类,实现类内部实现可看源码分析。而PasswordEncoder接口只有两个方法:

public interface PasswordEncoder {//密码加密String encode(CharSequence rawPassword);//密码配对boolean matches(CharSequence rawPassword, String encodedPassword);
}
复制代码

4 核心 Security 过滤器(Core Security Filters)

4.1 FilterSecurityInterceptor

  FilterSecurityInterceptor是Spring security授权模块入口,该类根据访问的用户的角色,权限授权访问那些资源(访问特定路径应该具备的权限)。
  FilterSecurityInterceptor封装FilterInvocation对象进行操作,所有的请求到了这一个filter,如果这个filter之前没有执行过的话,那么首先执行其父类AbstractSecurityInterceptor提供的InterceptorStatusToken token = super.beforeInvocation(fi),在此方法中使用AuthenticationManager获取Authentication中用户详情,使用ConfigAttribute封装已定义好访问权限详情,并使用AccessDecisionManager.decide()方法进行访问权限控制。
FilterSecurityInterceptor源码分析:

public void invoke(FilterInvocation fi) throws IOException, ServletException {if ((fi.getRequest() != null)&& (fi.getRequest().getAttribute(FILTER_APPLIED) != null)&& observeOncePerRequest) {fi.getChain().doFilter(fi.getRequest(), fi.getResponse());}else {// first time this request being called, so perform security checkingif (fi.getRequest() != null && observeOncePerRequest) {fi.getRequest().setAttribute(FILTER_APPLIED, Boolean.TRUE);}//回调其继承的抽象类AbstractSecurityInterceptor的方法InterceptorStatusToken token = super.beforeInvocation(fi);try {fi.getChain().doFilter(fi.getRequest(), fi.getResponse());}finally {super.finallyInvocation(token);}super.afterInvocation(token, null);}
}
复制代码

AbstractSecurityInterceptor源码分析:

protected InterceptorStatusToken beforeInvocation(Object object) {....//获取所有访问权限(url-role)属性列表(已定义在数据库或者其他地方)Collection<ConfigAttribute> attributes = this.obtainSecurityMetadataSource().getAttributes(object);....//获取该用户访问信息(包括url,访问权限)Authentication authenticated = authenticateIfRequired();// Attempt authorizationtry {//进行授权访问this.accessDecisionManager.decide(authenticated, object, attributes);}catch....
}
复制代码

4.2 UsernamePasswordAuthenticationFilter

  UsernamePasswordAuthenticationFilter使用username和password表单登录使用的过滤器,也是最为常用的过滤器。其源码:

public Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response) throws AuthenticationException {//获取表单中的用户名和密码String username = obtainUsername(request);String password = obtainPassword(request);...username = username.trim();//组装成username+password形式的tokenUsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);// Allow subclasses to set the "details" propertysetDetails(request, authRequest);//交给内部的AuthenticationManager去认证,并返回认证信息return this.getAuthenticationManager().authenticate(authRequest);
}
复制代码

  其主要代码为创建UsernamePasswordAuthenticationToken的Authentication实体以及调用AuthenticationManager进行authenticate认证,根据认证结果执行successfulAuthentication或者unsuccessfulAuthentication,无论成功失败,一般的实现都是转发或者重定向等处理,不再细究AuthenticationSuccessHandler和AuthenticationFailureHandle。兴趣的可以研究一下其父类AbstractAuthenticationProcessingFilter过滤器。

4.3 AnonymousAuthenticationFilter

AnonymousAuthenticationFilter是匿名登录过滤器,它位于常用的身份认证过滤器(如UsernamePasswordAuthenticationFilter、BasicAuthenticationFilter、RememberMeAuthenticationFilter)之后,意味着只有在上述身份过滤器执行完毕后,SecurityContext依旧没有用户信息,AnonymousAuthenticationFilter该过滤器才会有意义——基于用户一个匿名身份。 AnonymousAuthenticationFilter源码分析:

public class AnonymousAuthenticationFilter extends GenericFilterBean implementsInitializingBean {...public AnonymousAuthenticationFilter(String key) {this(key, "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));}...public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)throws IOException, ServletException {if (SecurityContextHolder.getContext().getAuthentication() == null) {//创建匿名登录Authentication的信息SecurityContextHolder.getContext().setAuthentication(createAuthentication((HttpServletRequest) req));...}chain.doFilter(req, res);}//创建匿名登录Authentication的信息方法protected Authentication createAuthentication(HttpServletRequest request) {AnonymousAuthenticationToken auth = new AnonymousAuthenticationToken(key,principal, authorities);auth.setDetails(authenticationDetailsSource.buildDetails(request));return auth;}
}
复制代码

4.4 SecurityContextPersistenceFilter

  SecurityContextPersistenceFilter的两个主要作用便是request来临时,创建SecurityContext安全上下文信息和request结束时清空SecurityContextHolder。源码后续分析。

小节总结:

. AbstractAuthenticationProcessingFilter:主要处理登录
. FilterSecurityInterceptor:主要处理鉴权

总结

  经过上面对核心的Component、Service、Filter分析,初步了解了Spring Security工作原理以及认证和授权工作流程。Spring Security认证和授权还有很多负责的过程需要深入了解,所以下次会对认证模块和授权模块进行更具体工作流程分析以及案例呈现。最后以上纯粹个人结合博客和官方文档总结,如有错请指出!

转载于:https://juejin.im/post/5d074dc1f265da1bce3dd10f

Spring security (一)架构框架-Component、Service、Filter分析相关推荐

  1. Spring Security(安全框架)

    一.概念 (1)Spring Security是一个高度自定义的安全框架.利用Spring IoC/DI和AOP功能,为系统提供了声明式安全访问控制功能,减少了为系统安全而编写大量重复代码的工作. ( ...

  2. spring security oauth2 架构---官方

    原文地址:https://projects.spring.io/spring-security-oauth/docs/oauth2.html Introduction This is the user ...

  3. 【Spring Security】安全框架学习(十三)

    6.1 自定义权限校验方法 我们也可以定义自己的权限校验方法,在@PreAuthorize注解中使用我们的方法. 我们可以发现直接在@PreAuthorize内写方法名就可以用默认提供的方法,那么怎么 ...

  4. spring security 注解_Spring框架使用@Autowired自动装配引发的讨论

    原文首发于掘金 作者:walkinger 链接:https://juejin.im/post/5d4163ede51d4561f64a078b 问题描述 有同事在开发新功能测试时,报了个错,大致就是, ...

  5. 【Spring Security】Spring Security框架详解

    文章目录 前言 一.框架概述 Spring Security的架构 Spring Security的主要特点 二.认证 HTTP Basic认证 表单登录 OpenID Connect 三.授权 基于 ...

  6. spring security_一文肝爆Spring安全框架Spring Security

    长按识别下方二维码,即可"关注"公众号 每天早晨,干货准时奉上! 作者:HallowCoder 序 Spring Security的架构及核心组件:(1)认证:(2)权限拦截:(3 ...

  7. Spring Security 架构简介

    一.技术概述 1.1 Spring vs Spring Boot vs Spring Security 1.1.1 Spring Framework Spring Framework 为开发 Java ...

  8. Spring Security权限框架简介

    一.框架介绍 Spring 是一个非常流行和成功的 Java 应用开发框架.Spring Security 是基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案.一般来说,Web  ...

  9. Spring Security(09)——Filter

    目录 1.1     Filter顺序 1.2     添加Filter到FilterChain 1.3     DelegatingFilterProxy 1.4     FilterChainPr ...

最新文章

  1. 调查:中国内地受访者每年花约40天用于各种“等”
  2. 解决dell poweredge 2850 服务器系统内存限制
  3. 人脸对齐--Unconstrained Face Alignment without Face Detection
  4. 如何建立java ssm工程_如何搭建一个ssm项目
  5. sql两个列值以下划线拼接得到一个新的列_面试必备sql知识点——MySQL基础
  6. 【转】WebService WSDL结构分析
  7. python随机颜色代码_python绘制随机颜色太阳花
  8. 4月8日--关于Date的练习题--自定义获取当前时间
  9. C++Primer第四版 阅读笔记 第二部分 “容器和算法”
  10. thinkphp路径引用问题
  11. JavaScript强化教程——AngularJS 表达式
  12. 多布局怎么搭建_展会搭建如何吸引人的注意力?
  13. 斗鱼开源基于Go实现的微服务框架 Jupiter
  14. 盈透api python封装_[转载]用MT4来接入IB盈透TWS平台交易外汇
  15. win10清除系统垃圾的几个命令
  16. windows10 DOS命令 小计
  17. 2021-07-04
  18. MySQL 教程(一)
  19. python - BeautifulSoup教程
  20. 【企业架构】现代企业架构方法——第 1 章

热门文章

  1. 时间插件只能选择整点和半点_我花一小时自制了三款PPT插件,不仅免费分享,还想手把手教你制作...
  2. delphi打印html文件路径,Delphi获取文件名、不带扩展名文件名、文件所在路径、上级文件夹路径的方法...
  3. pytorch forward_pytorch使用hook打印中间特征图、计算网络算力等
  4. 安卓手机充电慢_非 iPhone 12 独享,安卓系统手机也能用 MagSafe 充电|手机|安卓系统|充电器|安卓手机...
  5. 伪静态php配置,PHP开启伪静态配置
  6. matlab 计算N天前(后)的日期
  7. 李宏毅机器学习课程11~~~为何要深?
  8. 工作中的javascript代码收集及整理
  9. 如何寻找无序数组中的第K大元素?
  10. JSONModel的基本使用