Spring Security 认证过程
首页集成WebSecurityConfigurerAdapter并使用@EnableWebSecurity和@Configuration
WebSecurityConfigurerAdapter有三个方法分别是configure(WebSecurity web),configure(HttpSecurity http)和configure(AuthenticationManagerBuilder auth)
程序运行起来之后会首页进入到
从 源码可以看到会先进入到WebSecurityConfigurerAdapter中init()方法,然后进入到getHttp();
2.getHttp()中会先去获取AuthenticationManager这个类
3。而authenticationManager()方法会先去执行configure(AuthenticationManagerBuilder auth),由此可以知。程序运行之后最先执行的是configure(AuthenticationManagerBuilder auth),而这个方法主要是做什么用的呢?我们可以去看看上面的源码
4。我们进入到这个bulid()方法里面
5。然后进入到doBuild()方法中
6.再进入到performBuild()方法,可以看到我们会进入到AuthenticationManagerBuilder中的performBuild();而AuthenticationManagerBuilder正是上面说到configure(AuthenticationManagerBuilder auth)的参数
而performBuild()我们可以看到返回的是ProviderManager类,这个类是AuthenticationManager的实现类,实际认证都在这个类中进行。
自定义Filter完成验证码校验
自定义Filter 要 extends AbstractAuthenticationProcessingFilter,查看AbstractAuthenticationProcessingFilter的源码7.可以看到验证过程是执行了attemptAuthentication(request, response);
8.可以看到这个方法是UsernamePasswordAuthenticationFilter 集成 AbstractAuthenticationProcessingFilter后实现的过程最终会调用AuthenticantionManager.authenticate(authentication);也正是上面说到的实际是ProviderManager.authenticate(authentication)方法去执行验证。我们自定义的话也可以自己去覆盖attemptAuthentication(request, response)方法 并传入AuthenticantionManager,例如:
10.然后我们去研究研究ProviderManager.authenticate(authentication)里面是什么过程。
11.在这个方法可以看到是AuthenticationProvider 类执行的provider.authenticate(authentication);而AuthenticationProvider 在ProviderManager中是已集合的形式保存的
12.而ProviderManager的实例化我们在上面已经看到是在 AuthenticationManagerBuilder的performBuild()方法去完成的。
而AuthenticationProvider 是由AuthenticationManagerBuilder的authenticationProvider(AuthenticationProvider authenticationProvider)去提供的,如下图所示
且authenticationProvider(AuthenticationProvider authenticationProvider)是接口形式。
13.而authenticationProvider(authenticationProvider)中的authenticationProvider我们可以自定义authenticationProvider去实现AuthenticationProvider,如下图
最终验证的过程就在(Authentication authentication)中 就是第11步中provider.authenticate(authentication);
以上就是全部认证过程的逻辑。以前看源码之后没有记录,一段时间之后又忘记了,所以这一次记录一下方便以后看看。