当前位置: 首页 > 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.xdnf.cn/news/979849.html

相关文章:

  • BUG调试案例十四:TL431/TL432电路发热问题案例
  • Python训练营打卡DAY51
  • 机器学习核心概念速览
  • 基于ElasticSearch的法律法规检索系统架构实践
  • livetalking实时数字人多并发
  • uni-app项目实战笔记1--创建项目和实现首页轮播图功能
  • 告别excel:AI 驱动的数据分析指南
  • elementui使用Layout布局-对齐方式
  • input+disabled/readonly问题
  • Vue3 + TypeScript + Element Plus 表格行按钮不触发 row-click 事件、不触发勾选行,只执行按钮的 click 事件
  • Explore Image Deblurring via Encoded Blur Kernel Space论文阅读
  • 时序数据库IoTDB数据模型建模实例详解
  • Jmeter中变量如何使用?
  • MySQL 三表 JOIN 执行机制深度解析
  • 基础数论一一同余定理
  • Qt 动态插件系统QMetaObject::invokeMethod
  • 【docker】docker registry搭建私有镜像仓库
  • 开源 java android app 开发(十二)封库.aar
  • SD-WAN 技术如何助力工业物联网(IIoT)数据传输?深度解析传统方案对比与应用实践
  • Chrome 优质插件计划
  • 智慧农业物联网实训中心建设方案
  • 趋境科技英特尔生态沙龙举办,打通大模型私有化“最后一公里”
  • 当简约美学融入小程序 UI 设计:开启高效交互新篇
  • 【Java学习日记38】:C语言 fabs 与 Java abs 绝对值函数
  • element plus的el-form重置无效
  • CavityPlus: 北大团队研发的综合性蛋白质结合位点检测及功能分析网络服务器
  • 【python】预测投保人医疗费用,附insurance.csv数据集
  • 嵌入式系统内核镜像相关(三)
  • React 状态管理指南:Redux 原理与优化策略
  • 避坑:启动sdk-c demo master需要注意的事情