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

领域分解识别服务

相关推荐
星宸追风14 分钟前
Ubuntu更换Home目录所在硬盘的过程
linux·运维·ubuntu
制造数字化方案研究院28 分钟前
59页|PPT|华为集成服务交付ISD业务变革总体方案:业务规则、流程、IT、组织及度量“四位一体”的管理体系
运维·华为
热爱生活的猴子39 分钟前
Poetry 在 Linux 和 Windows 系统中的安装步骤
linux·运维·windows
渲吧-云渲染1 小时前
云渲染时,电脑能关机吗?关键阶段操作指南
运维·服务器·电脑
BD_Marathon1 小时前
Ubuntu下的Tomcat服务器部署
服务器·ubuntu·tomcat
m0_694845571 小时前
服务器需要备案吗?在哪些地区需要备案?
linux·运维·服务器·云计算
小眼睛FPGA1 小时前
【RK3568+PG2L50H开发板实验例程】Linux部分/FPGA dma_memcpy_demo 读写案例
linux·运维·科技·ai·fpga开发·gpu算力
weixin_437398211 小时前
转Go学习笔记
linux·服务器·开发语言·后端·架构·golang
南瓜胖胖2 小时前
【seismic unix 合并两个su文件】
服务器·unix
weixin_399380693 小时前
k8s一键部署tongweb企业版7049m6(by why+lqw)
java·linux·运维·服务器·云原生·容器·kubernetes