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

领域分解识别服务

相关推荐
寻道模式17 分钟前
【运维心得】完整教程:绕过Win11限制让老机焕发新生
运维·操作系统·win11
zzu123zsw21 分钟前
从 proxy_pass 末尾斜杠到 WebAssembly 预压缩:深挖 Nginx 生产环境四大高频踩坑点
运维·nginx·wasm·webassembly·devops·运维排错
中屹指纹浏览器svip21 分钟前
打开账号环境网页报错,常见原因有哪些?
服务器·开发语言·php·中屹指纹浏览器
2401_8685347833 分钟前
以太网物理层标准
服务器·网络
tg_xianheyun40 分钟前
亚马逊云服务器部署网站的步骤与上线检查清单
服务器·阿里云·云计算
张洛闻Eren42 分钟前
Ansible【第一课】:Ansible介绍
运维·数据库·云原生·kubernetes·github·ansible
郝亚军1 小时前
RK3562 中有 mosquitto、nginx 了,还需要 http,ftp,tftp 等协议吗?
运维·nginx·http
云边云科技_云网融合1 小时前
从 POS 机到访客 Wi-Fi:零售门店安全建设的完整解法
服务器·网络·数据库
hiahiahia1232 小时前
Message 和对话
服务器·前端·数据库
重生之小比特2 小时前
【Linux系统】07 进程状态
linux·运维·服务器