SpringSecurity原理剖析及其实战(四)

本文详细解读SpringSecurity的身份认证过程,包括认证原理、认证流程,以及关键接口如AuthenticationManager和AuthenticationProvider的作用。通过实例演示如何封装和验证用户凭证,并介绍了UserDetailsService和PasswordEncoder在实际项目中的运用。

SpringSecurity原理剖析及其实战(四)

1、认证原理

Spring Security是如何完成身份认证的?

  1. 用户名和密码被过滤器获取到,封装成Authentication,通常情况下是UsernamePasswordAuthenticationToken这个实现类。
  2. AuthenticationManager身份管理器负责验证这个Authentication
  3. 认证成功后,AuthenticationManager身份管理器返回一个被填充满了信息的(包括上面提到的权限信息,身份信息,细节信息,但密码通常会被移除)Authentication实例
  4. SecurityContextHolder安全上下文容器将第3步填充了信息的Authentication,通过 SecurityContextHolder.getContext().setAuthentication(…) 方法中,设置到其中。
public class AuthenticationExample {
   
   
    private static AuthenticationManager am = new SampleAuthenticationManager();
    public static void main(String[] args) throws Exception {
   
   
        BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
while (true) {
   
   
            System.out.println("Please enter your username:");
            String name = in.readLine();
            System.out.println("Please enter your password:");
            String password = in.readLine();
            try {
   
   
// 封装认证信息,未认证通过
                Authentication request = new
UsernamePasswordAuthenticationToken(name, password);
// 认证逻辑
Authentication result = am.authenticate(request); //当前线程绑定认证信息 SecurityContextHolder.getContext().setAuthentication(result); break;
            } catch (AuthenticationException</
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值