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博客

领域分解识别服务

相关推荐
TG:@yunlaoda360 云老大27 分钟前
阿里云国际站GPU:什么是GPU容器共享技术cGPU?实例命名规则是怎么样的?
服务器·阿里云·云计算
小草cys29 分钟前
华为910B服务器(搭载昇腾Ascend 910B AI 芯片的AI服务器查看服务器终端信息
服务器·人工智能·华为·昇腾·910b
dessler1 小时前
Elasticsearch(ES)Cerebro部署和使用
linux·运维·elasticsearch
an86950011 小时前
ubuntu 安装 JDK8
linux·运维·ubuntu
weixin_436525071 小时前
Docker 镜像导出与导入教程(Windows - Linux)
运维·docker·容器
小鹿学程序2 小时前
虚拟机之间配置免密登录(Centos)
大数据·linux·运维·centos
边疆.2 小时前
【Linux】编辑器vim的使用和理解gcc编译器
linux·运维·服务器·编辑器·vim
z10_142 小时前
什么是住宅IP,住宅IP应用场景有哪些
linux·服务器·tcp/ip
羑悻的小杀马特2 小时前
从零搭建群晖私有影音库:NasTool自动化追剧全流程拆解与远程访问协议优化实践
运维·数据库·自动化