SecurityContextHolder之策略模式源码分析

简介: SecurityContextHolder之策略模式源码分析

springsecurity 之 登录用户数据的获取

springsecurity中,用户登录信息本质是保存到HttpSession中,springsecurity进行封装 获取登录数据有两种思路:

  1. 从SecurityContextHolder中获取
  2. 从当前请求对象中获取

从SecurityContextHolder中获取

@RestController
public class HelloController {
    @GetMapping("/hello")
    public void hello() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println("authentication.getClass() = " + authentication.getClass());
    }
}

SecurityContextHolder存放的是SecurityContext ,SecurityContextHolder中定义三种不同的数据存储策略,采用了策略模式

  1. MODE_THREADLOCAL :将SecurityContext放在ThreadLocal中,开启子线程,子线程获取不到用户数据。
  2. MODE_INHERITABLETHREADLOCAL:多线程环境,子线程也能获取到用户数据。
  3. MODE_GLOBAL:数据保存到一个静态变量中,web开发中很少使用。

SecurityContextHolderStrategy接口用来规范存储策略中的方法

public interface SecurityContextHolderStrategy {
    void clearContext();

    SecurityContext getContext();

    void setContext(SecurityContext var1);

    SecurityContext createEmptyContext();
}

有三个实现类 对应三个不同的存储策略

ThreadLocalSecurityContextHolderStrategy

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.security.core.context;

import org.springframework.util.Assert;

final class ThreadLocalSecurityContextHolderStrategy implements SecurityContextHolderStrategy {
    private static final ThreadLocal<SecurityContext> contextHolder = new ThreadLocal();

    ThreadLocalSecurityContextHolderStrategy() {
    }

    public void clearContext() {
        contextHolder.remove();
    }

    public SecurityContext getContext() {
        SecurityContext ctx = (SecurityContext)contextHolder.get();
        if (ctx == null) {
            ctx = this.createEmptyContext();
            contextHolder.set(ctx);
        }

        return ctx;
    }

    public void setContext(SecurityContext context) {
        Assert.notNull(context, "Only non-null SecurityContext instances are permitted");
        contextHolder.set(context);
    }

    public SecurityContext createEmptyContext() {
        return new SecurityContextImpl();
    }
}

存储载体是ThreadLocal 针对SecurityContext的操作都是在ThreadLocal中进行操作。SecurityContext只是个接口,只有一个实现类是SecurityContextImpl

InheritableThreadLocalSecurityContextHolderStrategy

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.security.core.context;

import org.springframework.util.Assert;

final class InheritableThreadLocalSecurityContextHolderStrategy implements SecurityContextHolderStrategy {
    private static final ThreadLocal<SecurityContext> contextHolder = new InheritableThreadLocal();

    InheritableThreadLocalSecurityContextHolderStrategy() {
    }

    public void clearContext() {
        contextHolder.remove();
    }

    public SecurityContext getContext() {
        SecurityContext ctx = (SecurityContext)contextHolder.get();
        if (ctx == null) {
            ctx = this.createEmptyContext();
            contextHolder.set(ctx);
        }

        return ctx;
    }

    public void setContext(SecurityContext context) {
        Assert.notNull(context, "Only non-null SecurityContext instances are permitted");
        contextHolder.set(context);
    }

    public SecurityContext createEmptyContext() {
        return new SecurityContextImpl();
    }
}

存储载体为InheritableThreadLocal ,InheritableThreadLocal继承ThreadLocal,多了一个特性,就是在子线程创建的时间,会自动将父线程的数据复制到子线程中。实现了子线程中能够获取登录数据的功能。

GlobalSecurityContextHolderStrategy

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.security.core.context;

import org.springframework.util.Assert;

final class GlobalSecurityContextHolderStrategy implements SecurityContextHolderStrategy {
    private static SecurityContext contextHolder;

    GlobalSecurityContextHolderStrategy() {
    }

    public void clearContext() {
        contextHolder = null;
    }

    public SecurityContext getContext() {
        if (contextHolder == null) {
            contextHolder = new SecurityContextImpl();
        }

        return contextHolder;
    }

    public void setContext(SecurityContext context) {
        Assert.notNull(context, "Only non-null SecurityContext instances are permitted");
        contextHolder = context;
    }

    public SecurityContext createEmptyContext() {
        return new SecurityContextImpl();
    }
}

存储载体是一个静态变量,也可以在多线程环境下使用,但用的较少。

SecurityContextHolder源码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.security.core.context;

import java.lang.reflect.Constructor;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

public class SecurityContextHolder {
    public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL";
    public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL";
    public static final String MODE_GLOBAL = "MODE_GLOBAL";
    public static final String SYSTEM_PROPERTY = "spring.security.strategy";
    private static String strategyName = System.getProperty("spring.security.strategy");
    private static SecurityContextHolderStrategy strategy;
    private static int initializeCount = 0;

    public SecurityContextHolder() {
    }

    public static void clearContext() {
        strategy.clearContext();
    }

    public static SecurityContext getContext() {
        return strategy.getContext();
    }

    public static int getInitializeCount() {
        return initializeCount;
    }

    private static void initialize() {
        if (!StringUtils.hasText(strategyName)) {
            strategyName = "MODE_THREADLOCAL";
        }

        if (strategyName.equals("MODE_THREADLOCAL")) {
            strategy = new ThreadLocalSecurityContextHolderStrategy();
        } else if (strategyName.equals("MODE_INHERITABLETHREADLOCAL")) {
            strategy = new InheritableThreadLocalSecurityContextHolderStrategy();
        } else if (strategyName.equals("MODE_GLOBAL")) {
            strategy = new GlobalSecurityContextHolderStrategy();
        } else {
            try {
                Class<?> clazz = Class.forName(strategyName);
                Constructor<?> customStrategy = clazz.getConstructor();
                strategy = (SecurityContextHolderStrategy)customStrategy.newInstance();
            } catch (Exception var2) {
                ReflectionUtils.handleReflectionException(var2);
            }
        }

        ++initializeCount;
    }

    public static void setContext(SecurityContext context) {
        strategy.setContext(context);
    }

    public static void setStrategyName(String strategyName) {
        SecurityContextHolder.strategyName = strategyName;
        initialize();
    }

    public static SecurityContextHolderStrategy getContextHolderStrategy() {
        return strategy;
    }

    public static SecurityContext createEmptyContext() {
        return strategy.createEmptyContext();
    }

    public String toString() {
        return "SecurityContextHolder[strategy='" + strategyName + "'; initializeCount=" + initializeCount + "]";
    }

    static {
        initialize();
    }
}

SecurityContextHolder 定义三个静态常量描述三种不同存储策略,在静态代码块中初始化,根据不同的strategyName初始化不同的存储策略,可以调用配置系统变量或者调用setStrategyName改变策略。

在默认情况下,从子线程中获取登录数据是获取不到的,因为默认是MODE_THREADLOCAL策略。

存储策略在System.getProperty("spring.security.strategy");加载,可以配置系统变量来修改策略。

在VM option参数添加

-Dspring.security.strategy=MODE_INHERITABLETHREADLOCAL

SpringContextHolder默认将用户信息存储在ThreadLocal中,在SpringBoot中不同的请求使用不同的线程处理,是怎么获取到用户的信息的呢? 下篇文章揭晓,有懂的可以在评论区留言。

相关文章
|
10月前
|
存储 监控 前端开发
Java大文件上传解决方案:分片上传+断点续传实战
大文件上传通常指上传超过几百MB甚至几个GB的文件。与普通文件上传相比,大文件上传面临以下挑战:一次性加载整个文件到内存会导致内存溢出,上传过程中网络中断需要能够断点续传。
526 2
|
人工智能 API 开发者
阿里云百炼官网登录入口:首页和后台API管理调用控制台
阿里云百炼官网提供两大入口:一是平台介绍页,详述大模型能力、优势及定价,可免费领取最高5000万Tokens;二是管理控制台,用于获取API-KEY、调用API及查阅文档。开发者可通过对应链接快速开通服务并接入使用。
17278 1
|
10月前
|
存储 人工智能 安全
OpenClaw更新:9大新功能、50+Bug修复,附新版OpenClaw阿里云+本地部署及新功能实战攻略
2026年2月27日,OpenClaw迎来史诗级更新——v2026.2.26版本携近100项更新重磅发布,涵盖9大新功能、50+Bug修复,20+贡献者参与共建,40+PR合并,创下历史更新规模纪录。本次更新不仅实现安全性与架构能力的跨越式升级,更新增Android节点支持、外部密钥管理等核心功能,彻底重构Agent协作模式。本文将详解**2026年阿里云OpenClaw超简单部署流程**与**本地私有化部署方案**,深度拆解新版本5大重磅功能的实战用法,附带完整代码命令与避坑指南,帮助新老用户快速解锁AI协作新范式。
3629 2
|
10月前
|
人工智能 自然语言处理 Shell
OpenClaw 配置阿里云百炼 API 报错?这篇教你全解决
OpenClaw(原Moltbot/Clawdbot)是开源AI个人助手,支持本地部署与多平台接入。本文详解其对接阿里云百炼API的完整流程:安装配置、获取API Key、环境变量设置、JSON配置修改及模型验证,并推荐Qwen3-Max-Thinking等高性价比模型,新客首月低至0.3元/天。
4875 5
|
11月前
|
供应链 安全 物联网
微软365“设备代码钓鱼”风暴来袭:无需密码,黑客秒控企业邮箱
一种新型钓鱼攻击利用微软OAuth设备授权流程,通过真实登录页面诱导用户输入设备代码,从而绕过多因素认证,窃取企业账户权限。该攻击披着“合法”外衣,防不胜防,凸显安全与便利的平衡难题。
1919 0
|
Java
SpringBoot 发送邮箱验证码(HTML模板)
SpringBoot 发送邮箱验证码(HTML模板)
4515 0
SpringBoot 发送邮箱验证码(HTML模板)
|
缓存 Java Spring
servlet和SpringBoot两种方式分别获取Cookie和Session方式比较(带源码) —— 图文并茂 两种方式获取Header
文章比较了在Servlet和Spring Boot中获取Cookie、Session和Header的方法,并提供了相应的代码实例,展示了两种方式在实际应用中的异同。
2081 3
servlet和SpringBoot两种方式分别获取Cookie和Session方式比较(带源码) —— 图文并茂 两种方式获取Header
|
数据采集 JavaScript Java
CompletableFuture异步编排,你还不会?
本文介绍了同步与异步编程的概念,探讨了在复杂业务场景中使用异步编排的重要性。通过对比 `Future` 与 `CompletableFuture`,详细讲解了 `CompletableFuture` 的多种方法,如 `runAsync`、`supplyAsync`、`whenComplete`、`exceptionally` 等,并展示了如何通过 `CompletableFuture` 实现异步任务的组合与异常处理。最后,通过实战案例演示了如何利用线程池与 `CompletableFuture` 优化商品详情页的查询效率,显著减少响应时间。
899 3
CompletableFuture异步编排,你还不会?
|
XML Java 决策智能
拥抱智能决策新纪元!Spring Boot携手LiteFlow规则引擎,让复杂业务处理如丝般顺滑,引领技术潮流!
【8月更文挑战第29天】LiteFlow是一款专为Java应用设计的轻量级规则引擎,支持条件、循环、分支等多种规则类型,具有组件化设计和高度可扩展性。通过自定义规则和事件监听,它可以显著提升代码的可维护性和可重用性。本文将详细介绍如何在Spring Boot项目中整合LiteFlow,并通过实际案例演示其强大功能。主要步骤包括:添加依赖、配置参数、定义组件及流程,并通过API触发执行。借助LiteFlow,复杂业务逻辑处理变得更加灵活高效。
1281 0