当前位置: 首页 > news >正文

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

领域分解识别服务

http://www.dtcms.com/a/243911.html

相关文章:

  • 紫光展锐T8300以创新音频技术重塑感知世界
  • kafka-生产者(day-2)
  • python打卡第49天
  • 康谋方案 | 高精LiDAR+神经渲染3DGS的完美融合实践
  • 提升电子商务平台安全的有效策略
  • SSD,emmc 的写放大
  • k8s在节点上加污点
  • argocd部署cli工具并添加k8s集群
  • 数据安全进阶:30页数据安全管理培训精读【附全文阅读】
  • 跨域的本质与实战:从理论到松鼠短视频系统的演进-优雅草卓伊凡|卢健bigniu
  • window 显示驱动开发-如何查询视频处理功能(六)
  • 【Bluedroid】蓝牙启动之 RFCOMM_Init 流程源码解析
  • Android 默认第三方app运行权限(android11-13)
  • 【测试专栏】自动化测试——云存储项目
  • 计算机视觉与深度学习 | 基于Matlab的低照度图像增强算法原理,公式及实现
  • matlab红外与可见光图像配准算法
  • 学车笔记 变挡
  • 建站SEO优化之站点地图sitemap
  • Java多线程通信核心机制详解
  • UE5 学习系列(八)材质基础认知
  • 图数据库的理解
  • 【编译工具】(自动化)自动化测试工具:如何让我的开发效率提升300%并保证代码质量?
  • Ubuntu 22.04: 使用chroot切换到Ubuntu18.04运行环境进行开发编译
  • Roboguide工作站机器人重新安装软件包
  • Altair:让你爱上数据可视化的声明式魔法!
  • Hello Robot发布Stretch3机器人高保真模拟平台-Stretch MuJoCo v0.5-涵盖数百种Robocasa厨房应用测试场景
  • java转PHP开发需要几步?
  • 台湾TEMI协会竞赛——1、龙舟机器人组装教学
  • 七牛云域名配置与CNAME解析
  • 数据链抗干扰