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<GrantedAuthority> AUTHORITIES = new
    ArrayList<GrantedAuthority>();
    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博客

领域分解识别服务

相关推荐
翼龙云_cloud11 分钟前
云代理商:Hermes Agent在量化交易中的实战应用
运维·服务器·人工智能·ai智能体·hermes agent
七夜zippoe12 分钟前
DolphinDB时间序列引擎:实时聚合计算
服务器·前端·时间序列·dolphindb·实时聚合
木雷坞18 分钟前
Home Assistant Docker Compose 升级失败排查:镜像、备份和设备映射
服务器·docker·home assisant
m0_7381207219 分钟前
渗透测试基础知识——从零认识JWT(JSON Web Token)身份令牌
服务器·前端·安全·web安全·网络安全·json
无限进步_24 分钟前
【Linux】Makefile:让编译自动化
linux·运维·自动化
Jinkxs28 分钟前
LoadBalancer- 简单限流策略:Nginx 基于连接 / 请求的限流实现
java·运维·nginx
流浪00135 分钟前
告别静态打印:Linux C 实现实时刷新进度条
linux·运维·c语言
qq_1969761737 分钟前
硬核教程:用Gemini境像站构建端到端自动化办公工作流,告别重复操作(国内免费镜像实测)
运维·自动化
小此方38 分钟前
Re:Linux系统篇(二十)进程篇·五:深入理解 Linux 进程优先级:从底层逻辑到实战修改
linux·运维·服务器
流浪00142 分钟前
Linux篇(八) Make 与 Makefile 超详细入门教程|从零基础到手写自动化编译
linux·运维·自动化