SpringSecurity之UsernamePasswordAuthenticationFilter过滤器执行流程

本文详细介绍了Spring Security的登录认证过程,从UsernamePasswordAuthenticationFilter到AuthenticationManager,再到AuthenticationProvider的认证逻辑。重点讨论了Authentication对象的创建、自定义UserService以及如何扩展实现第三方登录的集成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

过滤器:UsernamePasswordAuthenticationFilter继承 AbstractAuthenticationProcessingFilter(抽象类)  

public class UsernamePasswordAuthenticationFilter extends

AbstractAuthenticationProcessingFilter {

}

核心方法,返回Authentication接口,里面有getAuthorities,getCredentials,getDetails,getPrincipal,isAuthenticated,setAuthenticated等方法

先执行attemptAuthentication方法。这个方法会从request中读出用户名、密码,组成UsernamePasswordAuthenticationToken对象,调用父类this.getAuthenticationManager().authenticate(authRequest)方法返回Authentication对象,UsernamePasswordAuthenticationToken是实现了Authentication。然后将Authentication对象传给AuthenticationManager进行登录认证。AuthenticationManager的认证过程是springsecurity认证的核心。大致记录下。

AuthenticationManager(接口)实际是ProviderManager(类),ProviderManager实现了AuthenticationManager接口。将认证的工作交给AuthenticationProvider(多个),AuthenticationManager都会包含多个AuthenticationProvider对象,有任何一个AuthenticationProvider验证通过,都属于认证通过。AuthenticationManager和AuthenticationProvider在哪里来的呢?在spring-security.xml的配置中来的

authenticate(authRequest)实现类ProviderManager

ProviderManager类核心方法循环遍历所有provider,有一个成功即认为通过

provider.authenticate(authentication)接口  AuthenticationProvider

实现类public abstract class AbstractUserDetailsAuthenticationProvider implements

AuthenticationProvider, InitializingBean, MessageSourceAware {}

UserDetails retrieveUser(String username,

UsernamePasswordAuthenticationToken authentication) 这个抽象方法实现类

核心方法

我们可以自定义userService 去重写loadByUsername(String username)方法

如果要自定义登录认证,如第三方登录后,用springsecurity接管,就需要增加类似于UsernamePasswordAuthenticationFilter的过滤器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值