当前位置: 首页 > 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博客

领域分解识别服务

相关文章:

  • 紫光展锐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 学习系列(八)材质基础认知
  • 上市公司专利查询网站/南京seo排名优化
  • 政府网站建设运营情况汇报/一个具体网站的seo优化
  • 南京做网站的公司/北京seo包年
  • 企业网站建设流程与方法 论文/合肥百度推广优化
  • 东莞模块网站建设方案/宁波优化网站厂家
  • 网站加一个会员登陆怎么做/成都网站seo诊断