美文网首页
spring security 校验大体流程

spring security 校验大体流程

作者: 骑着红驴逛青楼 | 来源:发表于2018-07-30 19:51 被阅读0次

    Spring Security是什么?

    Spring Security 和 shiro 一样都是基于java实现的安全框架!

    Spring Security是如何验证用户信息的,以及实现的机制?

    如果你用过shiro就会发现,shiro验证流程其实就是一个抽象类,封装了里面整体验证的流程,然后会暴露出几个接口或者是抽象方法,供自己灵活的去验证!这里用到的设计模式就是“模板模式

    spring security验证流程其实和shiro也是一样的,下面让我们看一下到底是哪个抽象类封装了整体的验证流程!

    AbstractAuthenticationProcessingFilter抽象类!!!

    具体步骤!

    上面的流程图就是spring security的整体验证流程!

    1.首先所有的请求都会走AbstractAuthenticationProcessingFilter.doFilter(req,res,chain)方法

    2.判断请求是否需要验证

    3.authResult = attemptAuthentication(request, response)进行用户验证(request中会带有用户的信息),该方法也是验证过程中最重要的方法

    1)返回一个 Authentication 对象,说明验证成功

    2)验证时发生 AuthenticationException。

    3)返回Null,表示身份验证不完整。假设子类做了一些必要的工作(如重定向)来继续处理验证,方法将立即返回。假设后一个请求将被这种方法接收,其中返回的Authentication对象不为空。

    接下来我们来看一下AbstractAuthenticationProcessingFilter到底是怎么搞得?

    首先AbstractAuthenticationProcessingFilter抽象类,咱们看一下继承它的子类

    从上图我们可以看出UsernamePasswordAuthenticationFilter类是它的子类,那么我们看一下UsernamePasswordAuthenticationFilter类attemptAuthentication(request, response)方法是怎么搞得

    从代码可以看出:

    1.首先用用户名和密码生成个token,

    2.然后去验证token;

    那么问题来了,是谁去验证的token?别急我们继续跟代码

    通过跟代码我们可以得出,原来AbstractAuthenticationProcessingFilter类中有一个private AuthenticationManager authenticationManager成员变量,也就是通过它去验证token;

    下面我们看一下AuthenticationManager 类:

    通过查看原来AuthenticationManager是一个验证管理器接口,既然是接口那一定有实现它的实现类!我们继续跟!!!

    通过查看代码,就ProviderManager类像正常点的!O(∩_∩)O哈哈~ 搜嘎~那我们继续看看ProviderManager是到底在搞什么猫腻~

    以上就是ProviderManager的authenticate(Authentication authentication),PS:它是实现AuthenticationManager接口的!!!

    主要看一下红线指向两处:

    1.有个这个东西【getProviders()】,然后遍历它,

    2.AuthenticationProvider对象去进行验证token!!【result = provider.authenticate(authentication)】;

    通过查看代码原来ProviderManager类里面有这个属性private List providers = Collections.emptyList();PS:也就是getProviders();

    既然干活的是AuthenticationProvider对象,那就再看看它是怎么搞得!

    AuthenticationProvider接口:

    AbstractUserDetailsAuthenticationProvider通过名字,你有没有什么想法?抽象的用户详情验证提供者!!!

    那么我们看一下authenticate(Authentication authentication)方法!

    retrieveUser方法:

    查看源码,他是一个抽象的方法;那接下来我们看一下它的实现类!DaoAuthenticationProvider

    看箭头,有没有什么茅塞顿开!!!

    this.getUserDetailsService().loadUserByUsername(username);就是我们自己实现的UserDetailsService接口的实现类,我们通过实现loadUserByUsername(username)方法,获取userDetail对象;然后通过additionalAuthenticationChecks方法检验!!!

    看到这里,如果之前没有用过spring security 的人一定会一头雾水~没事儿,多看看就好了,再结合网上的Demo自己感觉感觉!!!

    推荐Demo地址:http://www.spring4all.com/article/419

    总结:其实看着有点云里雾里~但是中心思想,就是把验证用户信息的一整套流程预先已经定义好了,封装在一个方法中(模板模式),然后各种暴露接口,抽象类,让子类去实现具体的业务逻辑!!!

    参考网址:http://www.spring4all.com/article/420

    相关文章

      网友评论

          本文标题:spring security 校验大体流程

          本文链接:https://www.haomeiwen.com/subject/exqqvftx.html