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 e) {
    System.out.println("Authentication failed: " + e.getMessage());
    }
    }
    System.out.println("Successfully authenticated. Security context
    contains: " +
    SecurityContextHolder.getContext().getAuthentication());
    }
    }
    class SampleAuthenticationManager implements AuthenticationManager {
    static final List AUTHORITIES = new
    ArrayList();
    static {
    AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
    }
    @Override
    public Authentication authenticate(Authentication auth) throws
    AuthenticationException {
    // 判断条件,用户名和密码是否相同
    if (auth.getName().equals(auth.getCredentials())) {
    // 封装认证信息,认证已通过
    return new UsernamePasswordAuthenticationToken(auth.getName(),
    auth.getCredentials(), AUTHORITIES);
    }
    throw new BadCredentialsException("Bad Credentials");
    }
    }

认证流程


推荐阅读

技术总体方案设计思路

如何评价代码的质量-CSDN博客

领域分解识别服务

相关推荐
AOwhisky8 小时前
Redis 学习笔记(第三期):持久化与主从复制
运维·数据库·redis·笔记·学习·云计算
c238569 小时前
Linux C++ 进度条进阶美化与工程化封装
linux·运维·服务器
李小白669 小时前
第四天-WEB服务器基本原理,IIS服务
运维·服务器·前端
2401_834636999 小时前
Nginx 从入门到实战:静态 / 动态站点、PHP 部署与反向代理全解析
运维·nginx·php
爱喝水的鱼丶9 小时前
SAP-ABAP:SAP视图开发入门:四类标准视图的适用场景与创建步骤详解
服务器·数据库·性能优化·sap·abap
aosky10 小时前
一台电脑配置多个 SSH Key 对应不同的 GitHub 账号
运维·ssh·github
云登指纹浏览器11 小时前
WebDriver反检测技术详解:如何让自动化脚本看起来像真实浏览器
运维·自动化·跨境电商
xmtxz11 小时前
计算机网络基础课程学习心得:从理论抽象到硬核实战的进阶之路
运维·学习
RisunJan12 小时前
Linux命令-pgrep (通过进程名查找进程 ID)
linux·运维
回忆2012初秋12 小时前
【Nginx】优雅地走进高性能 Web 服务器世界(1)
服务器·前端·nginx