服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - SpringSecurity认证流程详解

SpringSecurity认证流程详解

2021-05-05 11:07whyalwaysmea Java教程

这篇文章主要介绍了SpringSecurity认证流程详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

springsecurity基本原理

在之前的文章《springboot + spring security 基本使用及个性化登录配置》中对springsecurity进行了简单的使用介绍,基本上都是对于接口的介绍以及功能的实现。 这一篇文章尝试从源码的角度来上对用户认证流程做一个简单的分析。
在具体分析之前,我们可以先看看springsecurity的大概原理:

SpringSecurity认证流程详解

springsecurity基本原理

其实比较简单,主要是通过一系列的filter对请求进行拦截处理。

认证处理流程说明

我们直接来看usernamepasswordauthenticationfilter类,

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class usernamepasswordauthenticationfilter extends abstractauthenticationprocessingfilter
  // 登录请求认证
  public authentication attemptauthentication(httpservletrequest request, httpservletresponse response) throws authenticationexception {
    // 判断是否是post请求
    if (this.postonly && !request.getmethod().equals("post")) {
      throw new authenticationserviceexception("authentication method not supported: " + request.getmethod());
    } else {
      // 获取用户,密码
      string username = this.obtainusername(request);
      string password = this.obtainpassword(request);
      if (username == null) {
        username = "";
      }
 
      if (password == null) {
        password = "";
      }
 
      username = username.trim();
      // 生成token,
      usernamepasswordauthenticationtoken authrequest = new usernamepasswordauthenticationtoken(username, password);
      this.setdetails(request, authrequest);
      // 进一步验证
      return this.getauthenticationmanager().authenticate(authrequest);
    }
  }
}

attemptauthentication方法中,主要是进行username和password请求值的获取,然后再生成一个usernamepasswordauthenticationtoken 对象,进行进一步的验证。

不过我们可以先看看usernamepasswordauthenticationtoken 的构造方法

?
1
2
3
4
5
6
7
8
public usernamepasswordauthenticationtoken(object principal, object credentials) {
  // 设置空的权限
  super((collection)null);
  this.principal = principal;
  this.credentials = credentials;
  // 设置是否通过了校验
  this.setauthenticated(false);
}

其实usernamepasswordauthenticationtoken是继承于authentication,该对象在上一篇文章中有提到过,它是处理登录成功回调方法中的一个参数,里面包含了用户信息、请求信息等参数。

所以接下来我们看

?
1
this.getauthenticationmanager().authenticate(authrequest);

这里有一个authenticationmanager,但是真正调用的是providermanager

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class providermanager implements authenticationmanager, messagesourceaware, initializingbean {
  public authentication authenticate(authentication authentication) throws authenticationexception {
    class<? extends authentication> totest = authentication.getclass();
    authenticationexception lastexception = null;
    authentication result = null;
    boolean debug = logger.isdebugenabled();
    iterator var6 = this.getproviders().iterator();
 
    while(var6.hasnext()) {
      authenticationprovider provider = (authenticationprovider)var6.next();
      // 1.判断是否有provider支持该authentication
      if (provider.supports(totest)) {
        // 2. 真正的逻辑判断
        result = provider.authenticate(authentication);
      }
  }
}
  1. 这里首先通过provider判断是否支持当前传入进来的authentication,目前我们使用的是usernamepasswordauthenticationtoken,因为除了帐号密码登录的方式,还会有其他的方式,比如socialauthenticationtoken。
  2. 根据我们目前所使用的usernamepasswordauthenticationtoken,provider对应的是daoauthenticationprovider。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public authentication authenticate(authentication authentication) throws authenticationexception {
 
  userdetails user = this.usercache.getuserfromcache(username);
  if (user == null) {
    cachewasused = false;
    // 1.去获取userdetails
    user = this.retrieveuser(username, (usernamepasswordauthenticationtoken)authentication);
  }
 
  try {
    // 2.用户信息预检查
    this.preauthenticationchecks.check(user);
    // 3.附加的检查(密码检查)
    this.additionalauthenticationchecks(user, (usernamepasswordauthenticationtoken)authentication);
  } catch (authenticationexception var7) {   
  }
  // 4.最后的检查
  this.postauthenticationchecks.check(user);
  // 5.返回真正的经过认证的authentication
  return this.createsuccessauthentication(principaltoreturn, authentication, user);
}
  1. 去调用自己实现的userdetailsservice,返回userdetails
  2. 对userdetails的信息进行校验,主要是帐号是否被冻结,是否过期等
  3. 对密码进行检查,这里调用了passwordencoder
  4. 检查userdetails是否可用。
  5. 返回经过认证的authentication

这里的两次对userdetails的检查,主要就是通过它的四个返回boolean类型的方法。
经过信息的校验之后,通过usernamepasswordauthenticationtoken的构造方法,返回了一个经过认证的authentication。

拿到经过认证的authentication之后,会再去调用successhandler。或者未通过认证,去调用failurehandler。

认证结果如何在多个请求之间共享

再完成了用户认证处理流程之后,我们思考一下是如何在多个请求之间共享这个认证结果的呢?

因为没有做关于这方面的配置,所以可以联想到默认的方式应该是在session中存入了认证结果。

那么是什么时候存放入session中的呢?

我们可以接着认证流程的源码往后看,在通过attemptauthentication方法后,如果认证成功,会调用successfulauthentication,该方法中,不仅调用了successhandler,还有一行比较重要的代码

?
1
securitycontextholder.getcontext().setauthentication(authresult);

securitycontextholder是对于threadlocal的封装。 threadlocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有在指定线程中可以获取到存储的数据,对于其他线程来说则无法获取到数据。 更多的关于threadlocal的原理可以看看我以前的文章。

一般来说同一个接口的请求和返回,都会是在一个线程中完成的。我们在securitycontextholder中放入了authresult,再其他地方也可以取出来的。

最后就是在securitycontextpersistencefilter中取出了authresult,并存入了session

securitycontextpersistencefilter也是一个过滤器,它处于整个security过滤器链的最前方,也就是说开始验证的时候是最先通过该过滤器,验证完成之后是最后通过。

获取认证用户信息

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * 获取当前登录的用户
 * @return 完整的authentication
 */
@getmapping("/me1")
public object currentuser() {
  return securitycontextholder.getcontext().getauthentication();
}
 
@getmapping("/me2")
public object currentuser(authentication authentication) {
  return authentication;
}
 
/**
 * @param userdetails
 * @return 只包含了userdetails
 */
@getmapping("/me3")
public object cuurentuser(@authenticationprincipal userdetails userdetails) {
  return userdetails;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/u013435893/article/details/79605239

延伸 · 阅读

精彩推荐