欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Security 自定义短信登录认证的实现

程序员文章站 2022-06-26 16:30:32
自定义登录filter上篇文章我们说到,对于用户的登录,security通过定义一个filter拦截login路径来实现的,所以我们要实现自定义登录,需要自己定义一个filter,继承abstract...

自定义登录filter

上篇文章我们说到,对于用户的登录,security通过定义一个filter拦截login路径来实现的,所以我们要实现自定义登录,需要自己定义一个filter,继承abstractauthenticationprocessingfilter,从request中提取到手机号和验证码,然后提交给authenticationmanager:

public class smsauthenticationfilter extends abstractauthenticationprocessingfilter {
 public static final string spring_security_form_phone_key = "phone";
 public static final string spring_security_form_verify_code_key = "verifycode";
 private static final antpathrequestmatcher default_ant_path_request_matcher = new antpathrequestmatcher("/smslogin",
   "post");
 protected smsauthenticationfilter() {
  super(default_ant_path_request_matcher);
 }

 @override
 public authentication attemptauthentication(httpservletrequest request, httpservletresponse response) throws authenticationexception, ioexception, servletexception {
  string phone = request.getparameter(spring_security_form_phone_key);
  string verifycode = request.getparameter(spring_security_form_verify_code_key);
  if (stringutils.isblank(phone)){
   phone = "";
  }
  if (stringutils.isblank(verifycode)){
   verifycode = "";
  }
  smsauthenticationtoken authenticationtoken = new smsauthenticationtoken(phone, verifycode);
  setdetails(request,authenticationtoken);
  return getauthenticationmanager().authenticate(authenticationtoken);
 }

 protected void setdetails(httpservletrequest request, smsauthenticationtoken authrequest) {
  authrequest.setdetails(authenticationdetailssource.builddetails(request));
 }
}

其中smsauthenticationtoken参照usernamepasswordauthenticationtoken来实现:

public class smsauthenticationtoken extends abstractauthenticationtoken {
 private final object principal;
 private object credentials;

 public smsauthenticationtoken(object principal, object credentials) {
  super(null);
  this.principal = principal;
  this.credentials = credentials;
  //初始化完成,但是还未认证
  setauthenticated(false);
 }

 public smsauthenticationtoken(collection<? extends grantedauthority> authorities, object principal, object credentials) {
  super(authorities);
  this.principal = principal;
  this.credentials = credentials;
  setauthenticated(true);
 }

 @override
 public object getcredentials() {
  return credentials;
 }

 @override
 public object getprincipal() {
  return principal;
 }
}

自定义provider实现身份认证

我们知道authenticationmanager最终会委托给provider来实现身份验证,所以我们要判断验证码是否正确,需要自定义provider:

@slf4j
@component
public class smsauthenticationprovider implements authenticationprovider {
 @autowired
 private userdetailsservice userdetailsservice;

 @override
 public authentication authenticate(authentication authentication) {
  assert.isinstanceof(smsauthenticationtoken.class, authentication,
    () -> "smsauthenticationprovider.onlysupports only smsauthenticationtoken is supported");
  smsauthenticationtoken authenticationtoken = (smsauthenticationtoken) authentication;
  string phone = (string) authenticationtoken.getprincipal();
  string verifycode = (string) authenticationtoken.getcredentials();
  userdetails userdetails = userdetailsservice.loaduserbyusername(phone);
  if (userdetails == null){
   throw new internalauthenticationserviceexception("cannot get user info");
  }
  //验证码是否正确
  if (!stringutils.equals(cacheutil.getvalue(phone),verifycode)){
   throw new authenticationcredentialsnotfoundexception("验证码错误");
  }
  return new smsauthenticationtoken(userdetails.getauthorities(),userdetails,verifycode);
 }

 @override
 public boolean supports(class<?> authentication) {
  return authentication.isassignablefrom(smsauthenticationtoken.class);
 }
}

上面的cacheutil是封装的guava cache的实现,模拟发送验证码存储到内存中,在这个地方取出来做对比,如果对比失败就抛异常,对比成功就返回一个新的token,这个token中是包含了用户具有的权限的。

@slf4j
public class cacheutil {
 private static final loadingcache<string, string> cache = cachebuilder.newbuilder()
   //基于容量回收:总数量100个
   .maximumsize(100)
   //定时回收:没有写访问1分钟后失效清理
   .expireafterwrite(1, timeunit.minutes)
   //当在缓存中未找到所需的缓存项时,会执行cacheloader的load方法加载缓存
   .build(new cacheloader<string, string>() {
    @override
    public string load(string key) throws exception {
     log.debug("没有找到缓存: {}",key);
     return "";
    }
   });
 public static void putvalue(string key, string value){
  cache.put(key,value);
 }

 public static string getvalue(string key){
  try {
   return cache.get(key);
  } catch (executionexception e) {
   e.printstacktrace();
  }
  return "";
 }
}

身份认证结果回调

filter将手机号和验证码交给provider做验证,经过provider的校验,结果无非就两种,一种验证成功,一种验证失败,对于这两种不同的结果,我们需要实现两个handler,在获取到结果之后做回调。因为我们这儿只是简单的做url跳转,所以只需要继承simpleurlauthenticationsuccesshandler:

对于success的:

@component
public class smsauthsuccesshandler extends simpleurlauthenticationsuccesshandler {
 public smsauthsuccesshandler() {
  super("/index");
 }
}

对于failure的:

@component
public class smsauthfailurehandler extends simpleurlauthenticationfailurehandler {
 public smsauthfailurehandler() {
  super("/failure");
 }
}

上面整个登录流程的组件就完成了,接下来需要将它们整合起来。

整合登录组件

具体怎么整合,我们可以参考表单登录中,usernamepasswordauthenticationfilter是怎么整合进去的,回到配置类,还记得我们是怎么配置security的吗:

@configuration
public class securityconfig extends websecurityconfigureradapter {
 @override
 protected void configure(httpsecurity http) throws exception {
  http.formlogin()
    .loginpage("/login") //登录页面
    .successforwardurl("/index") //登录成功后的页面
    .failureforwardurl("/failure") //登录失败后的页面
    .and()
    // 设置url的授权
    .authorizerequests()
    // 这里需要将登录页面放行
    .antmatchers("/login")
    .permitall()
    //除了上面,其他所有请求必须被认证
    .anyrequest()
    .authenticated()
    .and()
    // 关闭csrf
    .csrf().disable();
 }
}

分析表单登录实现

看第一句,调用了http.formlogin(),在httpsecurity的formlogin方法定义如下:

public formloginconfigurer<httpsecurity> formlogin() throws exception {
 return getorapply(new formloginconfigurer<>());
}
private <c extends securityconfigureradapter<defaultsecurityfilterchain, httpsecurity>> c getorapply(c configurer)
 throws exception {
  //注意这个configure为securityconfigureradapter
 c existingconfig = (c) getconfigurer(configurer.getclass());
 if (existingconfig != null) {
 return existingconfig;
 }
 return apply(configurer);
}

apply方法为abstractconfiguredsecuritybuilder中的方法,我们目前先不关注它的实现,后面会仔细展开讲。现在只需要知道通过这个方法就能将configurer加入到security配置中。

这个地方添加了一个formloginconfigurer类,对于这个类官方给的解释为:

adds form based authentication. all attributes have reasonable defaults making all parameters are optional. if no #loginpage(string)} is specified, a default login page will be generated by the framework.

翻译过来就是:

添加基于表单的身份验证。所有属性都有合理的默认值,从而使所有参数都是可选的。如果未指定loginpage,则框架将生成一个默认的登录页面。

看一下它的构造方法:

public formloginconfigurer() {
 super(new usernamepasswordauthenticationfilter(), null);
 usernameparameter("username");
 passwordparameter("password");
}

发现usernamepasswordauthenticationfilter被传递给了父类,我们去它的父类abstractauthenticationfilterconfigurer看一下:

public abstract class abstractauthenticationfilterconfigurer<b extends httpsecuritybuilder<b>, t extends abstractauthenticationfilterconfigurer<b, t, f>, f extends abstractauthenticationprocessingfilter>
 extends abstracthttpconfigurer<t, b> {
 
 protected abstractauthenticationfilterconfigurer(f authenticationfilter, string defaultloginprocessingurl) {
 this();
  //这个filter就是usernamepasswordauthenticationfilter
 this.authfilter = authenticationfilter;
 if (defaultloginprocessingurl != null) {
 loginprocessingurl(defaultloginprocessingurl);
 }
 }
 
 @override
 public void configure(b http) throws exception {
 portmapper portmapper = http.getsharedobject(portmapper.class);
 if (portmapper != null) {
 this.authenticationentrypoint.setportmapper(portmapper);
 }
 requestcache requestcache = http.getsharedobject(requestcache.class);
 if (requestcache != null) {
 this.defaultsuccesshandler.setrequestcache(requestcache);
 }
  //通过getsharedobject获取共享对象。这里获取到authenticationmanager
 this.authfilter.setauthenticationmanager(http.getsharedobject(authenticationmanager.class));
  //设置成功和失败的回调
 this.authfilter.setauthenticationsuccesshandler(this.successhandler);
 this.authfilter.setauthenticationfailurehandler(this.failurehandler);
 if (this.authenticationdetailssource != null) {
 this.authfilter.setauthenticationdetailssource(this.authenticationdetailssource);
 }
 sessionauthenticationstrategy sessionauthenticationstrategy = http
 .getsharedobject(sessionauthenticationstrategy.class);
 if (sessionauthenticationstrategy != null) {
 this.authfilter.setsessionauthenticationstrategy(sessionauthenticationstrategy);
 }
 remembermeservices remembermeservices = http.getsharedobject(remembermeservices.class);
 if (remembermeservices != null) {
 this.authfilter.setremembermeservices(remembermeservices);
 }
 f filter = postprocess(this.authfilter);
  //添加filter
 http.addfilter(filter);
 }
}

可以看到这个地方主要做了三件事:

  • 将authenticationmanager设置到filter中
  • 添加成功/失败的回调
  • 将过滤器添加到过滤器链中

仿照表单登录,实现配置类

仿照上面的三个步骤,我们可以自己实现一个配置类,查看abstractauthenticationfilterconfigurer的类继承关系:

Spring Security 自定义短信登录认证的实现

它最上面的*父类为securityconfigureradapter,我们就继承它来实现我们基本的配置就行了(也可以继承abstracthttpconfigurer,没有歧视的意思),并且实现上面的三步:

@component
public class smsauthenticationsecurityconfig extends securityconfigureradapter<defaultsecurityfilterchain, httpsecurity> {
 @autowired
 private smsauthsuccesshandler smsauthsuccesshandler;
 @autowired
 private smsauthfailurehandler smsauthfailurehandler;
 @autowired
 private smsauthenticationprovider smsauthenticationprovider;
 @override
 public void configure(httpsecurity builder) throws exception {
  smsauthenticationfilter smsauthenticationfilter = new smsauthenticationfilter();
  smsauthenticationfilter.setauthenticationmanager(builder.getsharedobject(authenticationmanager.class));
  smsauthenticationfilter.setauthenticationsuccesshandler(smsauthsuccesshandler);
  smsauthenticationfilter.setauthenticationfailurehandler(smsauthfailurehandler);

  builder.authenticationprovider(smsauthenticationprovider);
  builder.addfilterafter(smsauthenticationfilter, usernamepasswordauthenticationfilter.class);
 }
}

和上面有一点不同,我们自定义的filter需要指定一下顺序,通过addfilterafter方法将我们的filter添加到过滤器链中,并且将自定义的provider也一并配置了进来。

添加配置到security中

这样我们的所有组件就已经组合到一起了,修改一下配置类:

@autowired
private smsauthenticationsecurityconfig smsauthenticationsecurityconfig;
@override
protected void configure(httpsecurity http) throws exception {
 http.formlogin()
  .loginpage("/login")
  .and()
  .apply(smsauthenticationsecurityconfig)
  .and()
  // 设置url的授权
  .authorizerequests()
  // 这里需要将登录页面放行
  .antmatchers("/login","/verifycode","/smslogin","/failure")
  .permitall()
  // anyrequest() 所有请求 authenticated() 必须被认证
  .anyrequest()
  .authenticated()
  .and()
  // 关闭csrf
  .csrf().disable();
}

再修改一下登录页面的登录接口和字段名:

<!doctype html>
<html lang="zh">
<head>
 <meta charset="utf-8">
 <title>login</title>
</head>
<body>
 <form action="/smslogin" method="post">
  <input type="text" name="phone"/>
  <input type="password" name="verifycode"/>
  <input type="submit" value="提交"/>
 </form>
</body>
</html>

这样通过短信验证码登录的功能就已经实现了。

建议大家可以自己重新实现一个自定义邮箱验证码登录,加深映像。

源码分析

configurer配置类工作原理

上面只是简单的使用,接下来我们分析configure是如何工作的。

大家注意自己要打开idea跟着过一遍源码

其实通过上面的配置我们可以发现,在security中的过滤器其实都是通过各种xxxconfigure来进行配置的,我们可以简单的理解为filter就是和配置类绑定在一起的。明白了这个概念,我们继续往下分析。
看上面abstractauthenticationfilterconfigurer的类继承关系图,从最上面开始分析,securitybuilder和securityconfigurer都是接口:

public interface securitybuilder<o> {
 /**
 * 构建一个对象并返回
 */
 o build() throws exception;
}
public interface securityconfigurer<o, b extends securitybuilder<o>> {
 /**
 * 初始化
 */
 void init(b builder) throws exception;
 void configure(b builder) throws exception;

}

securityconfigureradapter分析

上面两个接口的具体实现交给了securityconfigureradapter,在spring security中很多配置类都是继承自securityconfigureradapter来实现的。看一下实现类securityconfigureradapter的源码:

public abstract class securityconfigureradapter<o, b extends securitybuilder<o>> implements securityconfigurer<o, b> {

 private b securitybuilder;

 private compositeobjectpostprocessor objectpostprocessor = new compositeobjectpostprocessor();

 @override
 public void init(b builder) throws exception {
 }

 @override
 public void configure(b builder) throws exception {
 }

 /**
 * 返回securitybuilder,这样就可以进行链式调用了
 */
 public b and() {
 return getbuilder();
 }

 /**
 * 获取到securitybuilder
 */
 protected final b getbuilder() {
 assert.state(this.securitybuilder != null, "securitybuilder cannot be null");
 return this.securitybuilder;
 }

 /**
 * 执行对象的后置处理。默认值为委派给objectpostprocessor完成
 * @return 可使用的已修改对象
 */
 @suppresswarnings("unchecked")
 protected <t> t postprocess(t object) {
 return (t) this.objectpostprocessor.postprocess(object);
 }

 public void addobjectpostprocessor(objectpostprocessor<?> objectpostprocessor) {
 this.objectpostprocessor.addobjectpostprocessor(objectpostprocessor);
 }

 public void setbuilder(b builder) {
 this.securitybuilder = builder;
 }

 /**
 * objectpostprocessor的一个实现
 */
 private static final class compositeobjectpostprocessor implements objectpostprocessor<object> {
 private list<objectpostprocessor<?>> postprocessors = new arraylist<>();
 @override
 @suppresswarnings({ "rawtypes", "unchecked" })
 public object postprocess(object object) {
  //执行后置处理器的postprocess方法
 for (objectpostprocessor opp : this.postprocessors) {
 class<?> oppclass = opp.getclass();
 class<?> opptype = generictyperesolver.resolvetypeargument(oppclass, objectpostprocessor.class);
 if (opptype == null || opptype.isassignablefrom(object.getclass())) {
  object = opp.postprocess(object);
 }
 }
 return object;
 }
  //在list中添加了一个后置处理器
 private boolean addobjectpostprocessor(objectpostprocessor<?> objectpostprocessor) {
 boolean result = this.postprocessors.add(objectpostprocessor);
 this.postprocessors.sort(annotationawareordercomparator.instance);
 return result;
 }

 }
}

嗯。。。这两个方法都是空实现,应该是交给后面的子类去自己重写方法。多出来的内容就只是初始化了compositeobjectpostprocessor,并基于它封装了两个方法。

compositeobjectpostprocessor是objectpostprocessor的一个实现,objectpostprocessor实际上是一个后置处理器。
其次addobjectpostprocessor方法实际上就是在list中添加了一个后置处理器并排序。然后在postprocess方法中对这个list遍历,判断objectpostprocessor泛型类型和传过来的参数类型是否为父子关系,再次调用postprocess方法。

这个地方可能有点疑惑,为什么要再调用一次postprocess,这不就成递归了吗,我们注意一下compositeobjectpostprocessor类是private的,也就是只能在securityconfigureradapter内部使用,这里再次调用postprocess方法应该是其他的objectpostprocessor的实现。

可以看一下objectpostprocessor总共有两个实现,另外还有一个是autowirebeanfactoryobjectpostprocessor:

final class autowirebeanfactoryobjectpostprocessor
 implements objectpostprocessor<object>, disposablebean, smartinitializingsingleton {

 private final log logger = logfactory.getlog(getclass());

 private final autowirecapablebeanfactory autowirebeanfactory;

 private final list<disposablebean> disposablebeans = new arraylist<>();

 private final list<smartinitializingsingleton> smartsingletons = new arraylist<>();

 autowirebeanfactoryobjectpostprocessor(autowirecapablebeanfactory autowirebeanfactory) {
 assert.notnull(autowirebeanfactory, "autowirebeanfactory cannot be null");
 this.autowirebeanfactory = autowirebeanfactory;
 }

 @override
 @suppresswarnings("unchecked")
 public <t> t postprocess(t object) {
 if (object == null) {
 return null;
 }
 t result = null;
 try {
 result = (t) this.autowirebeanfactory.initializebean(object, object.tostring());
 }
 catch (runtimeexception ex) {
 class<?> type = object.getclass();
 throw new runtimeexception("could not postprocess " + object + " of type " + type, ex);
 }
 this.autowirebeanfactory.autowirebean(object);
 if (result instanceof disposablebean) {
 this.disposablebeans.add((disposablebean) result);
 }
 if (result instanceof smartinitializingsingleton) {
 this.smartsingletons.add((smartinitializingsingleton) result);
 }
 return result;
 }

 @override
 public void aftersingletonsinstantiated() {
 for (smartinitializingsingleton singleton : this.smartsingletons) {
 singleton.aftersingletonsinstantiated();
 }
 }

 @override
 public void destroy() {
 for (disposablebean disposable : this.disposablebeans) {
 try {
 disposable.destroy();
 }
 catch (exception ex) {
 this.logger.error(ex);
 }
 }
 }
}

这里面主要是通过autowirebeanfactory将对象注入到容器当中,在security中,很多对象都是new出来的,这些new出来的对象和容器没有任何关联,也不方便管理,所以通过autowirebeanfactoryobjectpostprocessor来完成对象的注入。

也就是说,在securityconfigureradapter中定义的这两个方法,其实就是将对象放进spring容器当中,方便管理。

abstractconfiguredsecuritybuilder分析

securityconfigureradapter的内容就这么多了,继续往下看abstracthttpconfigurer:

public abstract class abstracthttpconfigurer<t extends abstracthttpconfigurer<t, b>, b extends httpsecuritybuilder<b>>
 extends securityconfigureradapter<defaultsecurityfilterchain, b> {
 @suppresswarnings("unchecked")
 public b disable() {
 getbuilder().removeconfigurer(getclass());
 return getbuilder();
 }

 @suppresswarnings("unchecked")
 public t withobjectpostprocessor(objectpostprocessor<?> objectpostprocessor) {
 addobjectpostprocessor(objectpostprocessor);
 return (t) this;
 }
}

代码很少,第二个方法就是调用securityconfigureradapter的方法,这里主要看第一个disable方法,我们在配置类中就已经使用过了, 在禁用csrf的时候调用了 csrf().disable(),就是通过这个方法,将csrf的配置移除了。

继续看disable方法是调用了abstractconfiguredsecuritybuilder中的removeconfigurer方法,实际上就是移除linkedhashmap中的一个元素:

private final linkedhashmap<class<? extends securityconfigurer<o, b>>, list<securityconfigurer<o, b>>> configurers = new linkedhashmap<>();
public <c extends securityconfigurer<o, b>> list<c> removeconfigurers(class<c> clazz) {
 list<c> configs = (list<c>) this.configurers.remove(clazz);
 if (configs == null) {
 return new arraylist<>();
 }
 return new arraylist<>(configs);
 }

既然有移除的方法,那肯定就有添加的方法:

private final list<securityconfigurer<o, b>> configurersaddedininitializing = new arraylist<>();
private final map<class<?>, object> sharedobjects = new hashmap<>();
@suppresswarnings("unchecked")
private <c extends securityconfigurer<o, b>> void add(c configurer) {
 assert.notnull(configurer, "configurer cannot be null");
 class<? extends securityconfigurer<o, b>> clazz = (class<? extends securityconfigurer<o, b>>) configurer
  .getclass();
 synchronized (this.configurers) {
  if (this.buildstate.isconfigured()) {
   throw new illegalstateexception("cannot apply " + configurer + " to already built object");
  }
  list<securityconfigurer<o, b>> configs = null;
  if (this.allowconfigurersofsametype) {
   configs = this.configurers.get(clazz);
  }
  configs = (configs != null) ? configs : new arraylist<>(1);
  configs.add(configurer);
  this.configurers.put(clazz, configs);
  if (this.buildstate.isinitializing()) {
   this.configurersaddedininitializing.add(configurer);
  }
 }
}

我们自定义短信登录的时候,在配置类中添加自定义配置: .apply(smsauthenticationsecurityconfig),这个apply方法实际上就是调用上面的方法,将配置添加了进去。

既然配置都添加到这个容器当中了,那什么时候取出来用呢:

private collection<securityconfigurer<o, b>> getconfigurers() {
 list<securityconfigurer<o, b>> result = new arraylist<>();
 for (list<securityconfigurer<o, b>> configs : this.configurers.values()) {
 result.addall(configs);
 }
 return result;
}
//执行所有configurer的初始化方法
private void init() throws exception {
 collection<securityconfigurer<o, b>> configurers = getconfigurers();
 for (securityconfigurer<o, b> configurer : configurers) {
  configurer.init((b) this);
 }
 for (securityconfigurer<o, b> configurer : this.configurersaddedininitializing) {
  configurer.init((b) this);
 }
}
//获取到所有的configure,遍历执行configure方法
private void configure() throws exception {
 //从linkedhashmap中获取到configurer
 collection<securityconfigurer<o, b>> configurers = getconfigurers();
 for (securityconfigurer<o, b> configurer : configurers) {
  configurer.configure((b) this);
 }
}

在init和configure方法中,调用了配置类的configure方法,到这里其实整个流程就已经通了。

我们一般自定义登录,都会实现这个configure方法,在这个方法里初始化一个filter,然后加入到过滤器链中。
而这个类的init和configure方法,实际上是在调用securitybuilder 的build方法被调用的,具体的代码链路就不说了,大家感兴趣的可以自己去看一下。

最后贴一下abstractconfiguredsecuritybuilder的所有代码(已精简):

public abstract class abstractconfiguredsecuritybuilder<o, b extends securitybuilder<o>>
 extends abstractsecuritybuilder<o> {
 private final linkedhashmap<class<? extends securityconfigurer<o, b>>, list<securityconfigurer<o, b>>> configurers = new linkedhashmap<>();
 private final list<securityconfigurer<o, b>> configurersaddedininitializing = new arraylist<>();
 private final map<class<?>, object> sharedobjects = new hashmap<>();
 private final boolean allowconfigurersofsametype;
 private objectpostprocessor<object> objectpostprocessor;

 @suppresswarnings("unchecked")
 public <c extends securityconfigureradapter<o, b>> c apply(c configurer) throws exception {
 configurer.addobjectpostprocessor(this.objectpostprocessor);
 configurer.setbuilder((b) this);
 add(configurer);
 return configurer;
 }

 public <c extends securityconfigurer<o, b>> c apply(c configurer) throws exception {
 add(configurer);
 return configurer;
 }

 @suppresswarnings("unchecked")
 public <c> void setsharedobject(class<c> sharedtype, c object) {
 this.sharedobjects.put(sharedtype, object);
 }

 @suppresswarnings("unchecked")
 public <c> c getsharedobject(class<c> sharedtype) {
 return (c) this.sharedobjects.get(sharedtype);
 }

 /**
 * gets the shared objects
 * @return the shared objects
 */
 public map<class<?>, object> getsharedobjects() {
 return collections.unmodifiablemap(this.sharedobjects);
 }
 
 @suppresswarnings("unchecked")
 private <c extends securityconfigurer<o, b>> void add(c configurer) {
 assert.notnull(configurer, "configurer cannot be null");
 class<? extends securityconfigurer<o, b>> clazz = (class<? extends securityconfigurer<o, b>>) configurer
 .getclass();
 synchronized (this.configurers) {
 if (this.buildstate.isconfigured()) {
 throw new illegalstateexception("cannot apply " + configurer + " to already built object");
 }
 list<securityconfigurer<o, b>> configs = null;
 if (this.allowconfigurersofsametype) {
 configs = this.configurers.get(clazz);
 }
 configs = (configs != null) ? configs : new arraylist<>(1);
 configs.add(configurer);
 this.configurers.put(clazz, configs);
 if (this.buildstate.isinitializing()) {
 this.configurersaddedininitializing.add(configurer);
 }
 }
 }


 /**
 * 通过class name移除相关的配置类
 */
 @suppresswarnings("unchecked")
 public <c extends securityconfigurer<o, b>> list<c> removeconfigurers(class<c> clazz) {
 list<c> configs = (list<c>) this.configurers.remove(clazz);
 if (configs == null) {
 return new arraylist<>();
 }
 return new arraylist<>(configs);
 }

 /**
 * 通过class name移除相关的配置类
 */
 @suppresswarnings("unchecked")
 public <c extends securityconfigurer<o, b>> c removeconfigurer(class<c> clazz) {
 list<securityconfigurer<o, b>> configs = this.configurers.remove(clazz);
 if (configs == null) {
 return null;
 }
 assert.state(configs.size() == 1,
 () -> "only one configurer expected for type " + clazz + ", but got " + configs);
 return (c) configs.get(0);
 }

 @suppresswarnings("unchecked")
 public b objectpostprocessor(objectpostprocessor<object> objectpostprocessor) {
 assert.notnull(objectpostprocessor, "objectpostprocessor cannot be null");
 this.objectpostprocessor = objectpostprocessor;
 return (b) this;
 }

 protected <p> p postprocess(p object) {
 return this.objectpostprocessor.postprocess(object);
 }

 //执行所有configurer的初始化方法
 private void init() throws exception {
 collection<securityconfigurer<o, b>> configurers = getconfigurers();
 for (securityconfigurer<o, b> configurer : configurers) {
 configurer.init((b) this);
 }
 for (securityconfigurer<o, b> configurer : this.configurersaddedininitializing) {
 configurer.init((b) this);
 }
 }
 //获取到所有的configure,遍历执行configure方法
 private void configure() throws exception {
  //从linkedhashmap中获取到configurer
 collection<securityconfigurer<o, b>> configurers = getconfigurers();
 for (securityconfigurer<o, b> configurer : configurers) {
 configurer.configure((b) this);
 }
 }
 //执行钩子函数和configure方法
 protected final o dobuild() throws exception {
 synchronized (this.configurers) {
 this.buildstate = buildstate.initializing;
 beforeinit();
 init();
 this.buildstate = buildstate.configuring;
 beforeconfigure();
 configure();
 this.buildstate = buildstate.building;
 o result = performbuild();
 this.buildstate = buildstate.built;
 return result;
 }
 }
}

到此这篇关于spring security 自定义短信登录认证的实现的文章就介绍到这了,更多相关springsecurity 短信登录认证内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!