当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Security登录验证流程源码解析

Spring Security登录验证流程源码解析

2019年11月18日  | 移动技术网IT编程  | 我要评论

一、登录认证基于过滤器链

spring security的登录验证流程核心就是过滤器链。当一个请求到达时按照过滤器链的顺序依次进行处理,通过所有过滤器链的验证,就可以访问api接口了。

file

springsecurity提供了多种登录认证的方式,由多种filter过滤器来实现,比如:

  • basicauthenticationfilter实现的是httpbasic模式的登录认证
  • usernamepasswordauthenticationfilter实现用户名密码的登录认证
  • remembermeauthenticationfilter实现登录认证的“记住我”的功能
  • smscodeauthenticationfilter实现短信验证码登录认证
  • socialauthenticationfilter实现社交媒体方式登录认证的处理
  • oauth2authenticationprocessingfilter和oauth2clientauthenticationprocessingfilter实现oauth2的鉴权方式

根据我们不同的需求实现及配置,不同的filter会被加载到应用中。

二、结合源码讲解登录验证流程

我们就以用户名、密码登录方式为例讲解一下spring security的登录认证流程。

file

2.1 usernamepasswordauthenticationfilter

该过滤器封装用户基本信息(用户名、密码),定义登录表单数据接收相关的信息。如:

  • 默认的表单用户名密码input框name是username、password
  • 默认的处理登录请求路径是/login、使用post方法

file
file

2.2 abstractauthenticationprocessingfilter的dofilter方法的验证过程

usernamepasswordauthenticationfilter继承自抽象类abstractauthenticationprocessingfilter,该抽象类定义了验证成功与验证失败的处理方法。
file

2.3 验证成功之后的handler和验证失败之后的handler

file

也就是说当我们需要自定义验证成功或失败的处理方法时,要去实现authenticationsuccesshandler或authenticationfailurehandler接口

file

三、登录验证内部细节

3.1多种认证方式的管理 providermanager

providermanager用继承于authenticationmanager是登录验证的核心类。providermanager保管了多个authenticationprovider,用于不同类型的登录验证。比如:

  • remembermeauthenticationprovider定义了“记住我”功能的登录验证逻辑
  • daoauthenticationprovider加载数据库用户信息,进行用户密码的登录验证
public class providermanager implements authenticationmanager, messagesourceaware, initializingbean {
    ……
    private list<authenticationprovider> providers;
    ……

下文是providermanager的核心源码,遍历不同登录验证的authenticationprovider,只有当这种方式被支持的时候,才执行具体的登录验证逻辑。
file

3.2 登录认证接口 authenticationprovider

public interface authenticationprovider {
    authentication authenticate(authentication var1) throws authenticationexception;

    boolean supports(class<?> var1);
}

authenticationprovider的实现类定义了具体的登录验证逻辑

file

3.3 数据库加载用户信息 daoauthenticationprovider

public class daoauthenticationprovider extends abstractuserdetailsauthenticationprovider {

从数据库获取用户信息源码

file

所以当我们需要加载用户信息进行登录验证的时候,我们需要实现userdetailsservice接口,重写loaduserbyusername方法,参数是用户输入的用户名。返回值是userdetails

期待您的关注

  • 博主最近新写了一本书:
  • 本文转载注明出处(必须带连接,不能只转文字):。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网