• 多线程异步方法Spring Security框架的SecurityContext无法获取认证信息的原因及解决方案


          Spring Security是Spring生态提供的用户应用安全保护的一个安全框架,其提供了一种高度可定制的实现身份认证(Authentication),授权(Authorization)以及对常见的web攻击手段做防护的方法。

          之前我的博客Oauth2与Spring Security框架的认证授权管理讲到过,使用Spring Security结合Oauth2进行身份认证,以及授权集成到项目的步骤。

        在集成成功后,每次接口的请求,都会在请求头中携带Authrization的请求头,携带access-token信息,然后在项目中使用SecutityContext对象就可以获取到用户身份信息。

        一般在项目中会创建一个工具类,用来获取用户信息,其中就是使用的SecutityContext进行封装的工具类。

         比如我在项目中创建了一个UserUtil工具类:

    1. package com.xiaomifneg1010.module.visit.system.util;
    2. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
    3. import com.xiaomifneg1010.base.config.security.support.MyUserDetails;
    4. import com.xiaomifneg1010.module.common.enums.system.UserLevelEnum;
    5. import com.xiaomifneg1010.module.common.model.system.UserLevelVo;
    6. import com.xiaomifneg1010.module.system.dept.entity.Dept;
    7. import com.xiaomifneg1010.module.system.dept.service.DeptService;
    8. import com.xiaomifneg1010.module.system.deptusermid.entity.DeptUserMid;
    9. import com.xiaomifneg1010.module.system.deptusermid.service.DeptUserMidService;
    10. import com.xiaomifneg1010.module.system.user.entity.User;
    11. import com.xiaomifneg1010.module.system.user.service.UserService;
    12. import com.xiaomifneg1010.module.visit.system.service.BusUserService;
    13. import lombok.RequiredArgsConstructor;
    14. import org.apache.commons.lang3.StringUtils;
    15. import org.springframework.security.core.context.SecurityContextHolder;
    16. import org.springframework.stereotype.Component;
    17. import java.util.ArrayList;
    18. import java.util.List;
    19. import java.util.Objects;
    20. /**
    21. * @author xiaomifeng1010
    22. * @version 1.0
    23. * @date:
    24. * @Description
    25. */
    26. @Component
    27. @RequiredArgsConstructor
    28. public class UserUtil {
    29. private final UserService userService;
    30. private final DeptUserMidService deptUserMidService;
    31. private final DeptService deptService;
    32. List deptIdList=new ArrayList<>();
    33. /**
    34. * @description: 获取当前用户账号
    35. * @author: xiaomifeng1010
    36. * @date:
    37. * @param
    38. * @return: String
    39. **/
    40. public String getUserAccount(){
    41. MyUserDetails userDetails = (MyUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    42. String userAccount = userDetails.getUsername();
    43. return userAccount;
    44. }
    45. /**
    46. * @description: 获取userId
    47. * @author:xiaomifeng1010
    48. * @date:
    49. * @param
    50. * @return: Long
    51. **/
    52. public Long getUserId(){
    53. String userAccount = getUserAccount();
    54. return userService.getObj(Wrappers. lambdaQuery()
    55. .select(User ::getId).eq(User ::getUserAccount,userAccount ),a -> Long.valueOf(String.valueOf(a)));
    56. }
    57. public User getUserInfo(){
    58. String userAccount = getUserAccount();
    59. return userService.getOne(Wrappers. lambdaQuery()
    60. .eq(User ::getUserAccount,userAccount ));
    61. }
    62. /**
    63. * @description: 获取当前用户的主部门id
    64. * @author:xiaomifeng1010
    65. * @date: 2022/4/11
    66. * @param
    67. * @return: Long
    68. **/
    69. public Long getMasterDeptId(){
    70. Long userId = getUserId();
    71. return deptUserMidService.getObj(Wrappers. lambdaQuery()
    72. .select(DeptUserMid::getDeptid).eq(DeptUserMid::getUserid,userId).eq(DeptUserMid::getIsmaster,1),
    73. a ->Long.valueOf(String.valueOf(a)));
    74. }
    75. public String getDeptCode(){
    76. Long masterDeptId = getMasterDeptId();
    77. Dept dept = deptService.getById(masterDeptId);
    78. return Objects.nonNull(dept) ? dept.getDeptcode() : StringUtils.EMPTY;
    79. }
    80. /**
    81. * @description: 获取所在主部门以及子级部门
    82. * @author: xiaomifeng1010
    83. * @date:
    84. * @param deptId 主部门id
    85. * @return: List
    86. **/
    87. public List getDeptIdList(Long deptId){
    88. deptIdList.add(deptId);
    89. Long childDeptId = deptService.getObj(Wrappers.lambdaQuery()
    90. .select(Dept::getId)
    91. .eq(Dept::getParentid, deptId), a -> Long.valueOf(a.toString()));
    92. if (Objects.nonNull(childDeptId)){
    93. getDeptIdList(childDeptId);
    94. }
    95. return deptIdList;
    96. }
    97. }

    Spring Security的安全上下文是由SecurityContext接口描述的。

    1. /*
    2. * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
    3. *
    4. * Licensed under the Apache License, Version 2.0 (the "License");
    5. * you may not use this file except in compliance with the License.
    6. * You may obtain a copy of the License at
    7. *
    8. * https://www.apache.org/licenses/LICENSE-2.0
    9. *
    10. * Unless required by applicable law or agreed to in writing, software
    11. * distributed under the License is distributed on an "AS IS" BASIS,
    12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13. * See the License for the specific language governing permissions and
    14. * limitations under the License.
    15. */
    16. package org.springframework.security.core.context;
    17. import org.springframework.security.core.Authentication;
    18. import java.io.Serializable;
    19. /**
    20. * Interface defining the minimum security information associated with the current thread
    21. * of execution.
    22. *
    23. *

    24. * The security context is stored in a {@link SecurityContextHolder}.
    25. *

    26. *
    27. * @author Ben Alex
    28. */
    29. public interface SecurityContext extends Serializable {
    30. // ~ Methods
    31. // ========================================================================================================
    32. /**
    33. * Obtains the currently authenticated principal, or an authentication request token.
    34. *
    35. * @return the Authentication or null if no authentication
    36. * information is available
    37. */
    38. Authentication getAuthentication();
    39. /**
    40. * Changes the currently authenticated principal, or removes the authentication
    41. * information.
    42. *
    43. * @param authentication the new Authentication token, or
    44. * null if no further authentication information should be stored
    45. */
    46. void setAuthentication(Authentication authentication);
    47. }

    从源码中可以看出这个接口的主要职责就是存储身份认证对象和获取身份认证对象的,那么SecurityContext本身是如何被管理的呢?Spring Security框架提供了3种策略来管理SecurityContext.管理该类的对象是SecurityContextHolder.

    这3种策略也定义在了SecurityContextHolder类中:

    1. /*
    2. * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
    3. *
    4. * Licensed under the Apache License, Version 2.0 (the "License");
    5. * you may not use this file except in compliance with the License.
    6. * You may obtain a copy of the License at
    7. *
    8. * https://www.apache.org/licenses/LICENSE-2.0
    9. *
    10. * Unless required by applicable law or agreed to in writing, software
    11. * distributed under the License is distributed on an "AS IS" BASIS,
    12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13. * See the License for the specific language governing permissions and
    14. * limitations under the License.
    15. */
    16. package org.springframework.security.core.context;
    17. import org.springframework.util.ReflectionUtils;
    18. import org.springframework.util.StringUtils;
    19. import java.lang.reflect.Constructor;
    20. /**
    21. * Associates a given {@link SecurityContext} with the current execution thread.
    22. *

    23. * This class provides a series of static methods that delegate to an instance of
    24. * {@link org.springframework.security.core.context.SecurityContextHolderStrategy}. The
    25. * purpose of the class is to provide a convenient way to specify the strategy that should
    26. * be used for a given JVM. This is a JVM-wide setting, since everything in this class is
    27. * static to facilitate ease of use in calling code.
    28. *

    29. * To specify which strategy should be used, you must provide a mode setting. A mode
    30. * setting is one of the three valid MODE_ settings defined as
    31. * static final fields, or a fully qualified classname to a concrete
    32. * implementation of
    33. * {@link org.springframework.security.core.context.SecurityContextHolderStrategy} that
    34. * provides a public no-argument constructor.
    35. *

    36. * There are two ways to specify the desired strategy mode String. The first
    37. * is to specify it via the system property keyed on {@link #SYSTEM_PROPERTY}. The second
    38. * is to call {@link #setStrategyName(String)} before using the class. If neither approach
    39. * is used, the class will default to using {@link #MODE_THREADLOCAL}, which is backwards
    40. * compatible, has fewer JVM incompatibilities and is appropriate on servers (whereas
    41. * {@link #MODE_GLOBAL} is definitely inappropriate for server use).
    42. *
    43. * @author Ben Alex
    44. *
    45. */
    46. public class SecurityContextHolder {
    47. // ~ Static fields/initializers
    48. // =====================================================================================
    49. public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL";
    50. public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL";
    51. public static final String MODE_GLOBAL = "MODE_GLOBAL";
    52. public static final String SYSTEM_PROPERTY = "spring.security.strategy";
    53. private static String strategyName = System.getProperty(SYSTEM_PROPERTY);
    54. private static SecurityContextHolderStrategy strategy;
    55. private static int initializeCount = 0;
    56. static {
    57. initialize();
    58. }
    59. // ~ Methods
    60. // ========================================================================================================
    61. /**
    62. * Explicitly clears the context value from the current thread.
    63. */
    64. public static void clearContext() {
    65. strategy.clearContext();
    66. }
    67. /**
    68. * Obtain the current SecurityContext.
    69. *
    70. * @return the security context (never null)
    71. */
    72. public static SecurityContext getContext() {
    73. return strategy.getContext();
    74. }
    75. /**
    76. * Primarily for troubleshooting purposes, this method shows how many times the class
    77. * has re-initialized its SecurityContextHolderStrategy.
    78. *
    79. * @return the count (should be one unless you've called
    80. * {@link #setStrategyName(String)} to switch to an alternate strategy.
    81. */
    82. public static int getInitializeCount() {
    83. return initializeCount;
    84. }
    85. private static void initialize() {
    86. if (!StringUtils.hasText(strategyName)) {
    87. // Set default
    88. strategyName = MODE_THREADLOCAL;
    89. }
    90. if (strategyName.equals(MODE_THREADLOCAL)) {
    91. strategy = new ThreadLocalSecurityContextHolderStrategy();
    92. }
    93. else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) {
    94. strategy = new InheritableThreadLocalSecurityContextHolderStrategy();
    95. }
    96. else if (strategyName.equals(MODE_GLOBAL)) {
    97. strategy = new GlobalSecurityContextHolderStrategy();
    98. }
    99. else {
    100. // Try to load a custom strategy
    101. try {
    102. Class clazz = Class.forName(strategyName);
    103. Constructor customStrategy = clazz.getConstructor();
    104. strategy = (SecurityContextHolderStrategy) customStrategy.newInstance();
    105. }
    106. catch (Exception ex) {
    107. ReflectionUtils.handleReflectionException(ex);
    108. }
    109. }
    110. initializeCount++;
    111. }
    112. /**
    113. * Associates a new SecurityContext with the current thread of execution.
    114. *
    115. * @param context the new SecurityContext (may not be null)
    116. */
    117. public static void setContext(SecurityContext context) {
    118. strategy.setContext(context);
    119. }
    120. /**
    121. * Changes the preferred strategy. Do NOT call this method more than once for
    122. * a given JVM, as it will re-initialize the strategy and adversely affect any
    123. * existing threads using the old strategy.
    124. *
    125. * @param strategyName the fully qualified class name of the strategy that should be
    126. * used.
    127. */
    128. public static void setStrategyName(String strategyName) {
    129. SecurityContextHolder.strategyName = strategyName;
    130. initialize();
    131. }
    132. /**
    133. * Allows retrieval of the context strategy. See SEC-1188.
    134. *
    135. * @return the configured strategy for storing the security context.
    136. */
    137. public static SecurityContextHolderStrategy getContextHolderStrategy() {
    138. return strategy;
    139. }
    140. /**
    141. * Delegates the creation of a new, empty context to the configured strategy.
    142. */
    143. public static SecurityContext createEmptyContext() {
    144. return strategy.createEmptyContext();
    145. }
    146. @Override
    147. public String toString() {
    148. return "SecurityContextHolder[strategy='" + strategyName + "'; initializeCount="
    149. + initializeCount + "]";
    150. }
    151. }

      然后介绍一下这3种策略:

    MODE_THREALOCAL: 允许每个线程在安全上下文存储自己的详细信息,在每个请求一个线程的web应用程序中,这是一种常见的方法,因为每个请求都是一个单独的线程。这个策略也是Spring Security默认使用的策略。

    MODE_INHERITABLETHREADLOCAL: 类似于MODE_THREALOCAL,但是从名称中可以知道,这是一个可以继承的模式,所以这种模式,可以在使用异步方法时,将安全上下文复制到下一个线程,这样再运行带有@Async注解的异步方法时,调用该方法的线程也能继承到该安全上下文。

    MODE_GLOBAL:使引用程序的所欲线程看到相同的安全上下文实例。

    由于Spring Security默认使用的是 MODE_THREALOCAL模式,该模式只允许在请求的主线程中获取安全上下文信息,用来获取用户身份信息,所以如果请求的接口中,又调用了异步方法,或者自定义了线程池去执行方法,则会获取不到用户信息,并且出现NullPointerException异常.

    默认策略使用ThreadLocal管理上下文,ThreadLocal是JDK提供的实现,该实现作为数据集合来执行,但会确保应用程序的每个线程只能看到存储在集合中的数据,这样,每个请求都可以访问各自的安全上下文。线程之间不可以访问到其他线程的ThreadLocal。每个请求只能看到自己的安全上下文。确保线程获取的用户信息的准确性。

         注意:每个请求绑定一个线程这种架构只适用于传统的Servlet应用程序,其中每个请求都被分配了自己的线程。它不适用于响应式编程程序。

       如果我们在请求接口中调用了@Async注解的异步方法。那么就需要自定义配置,修改程序默认的策略。定义配置也很简单,只需要在配置类中注入一个bean即可,覆盖Spring Security默认的安全上下文策略即可:

       配置代码如下:

    1. * @description: 使异步任务可以继承安全上下文(SecurityContext);
    2. * 注意,该方法只适用于spring 框架本身创建线程时使用(例如,在使用@Async方法时),这种方法才有效;
    3. * 如果是在代码中手动创建线程,则需要使用{@link org.springframework.security.concurrent.DelegatingSecurityContextRunnable}
    4. * 或者{@link org.springframework.security.concurrent.DelegatingSecurityContextCallable},
    5. * 当然使用{@link org.springframework.security.concurrent.DelegatingSecurityContextExecutorService}
    6. * 来转发安全上下文更好
    7. * @author: xiaomifeng1010
    8. * @date:
    9. * @param
    10. * @return: InitializingBean
    11. **/
    12. @Bean
    13. public InitializingBean initializingBean(){
    14. return () -> SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
    15. }

    但是这种方式仅适用于可以被Spring管理的线程。但是还有一种情况就是我们自己手动创建的线程池,Spring框架是没有进行管理的,或者说是不被Spirng框架知道的,这种线程称为自管理线程,针对这种情况,应该如何处理呢?好在Spring Security提供了一些实用的工具,将有助于将安全上下文传播到新创建的线程。

      SecurityContextHolder如果要处理自己定义的线程任务传递安全上下文是没有指定策略的。在这种情况下,如果我们需要安全上下文在线程之间传播。用于此目的的一种解决方案是使用DelegatingSecurityContextRunnable装饰想要在单独线程上执行的任务。DelegatingSecurityContextRunnable拓展了Runnable接口。当不需要预期的值时,则可以在任务执行时使用它。如果需要返回值,则可以使用DelegatingSecurityContextCallable。这两个类用于处理异步执行的任务。

    例如要将任务提交给ExecutorService执行,

    1. package com.xiaomifneg1010;
    2. import com.xiaomifneg1010.base.config.security.support.MyUserDetails;
    3. import com.google.common.util.concurrent.ThreadFactoryBuilder;
    4. import org.springframework.security.concurrent.DelegatingSecurityContextCallable;
    5. import org.springframework.security.concurrent.DelegatingSecurityContextExecutorService;
    6. import org.springframework.security.core.context.SecurityContextHolder;
    7. import java.util.concurrent.*;
    8. /**
    9. * @author xiaomifeng1010
    10. * @version 1.0
    11. * @date:
    12. * @Description
    13. */
    14. public class Test {
    15. public static void main(String[] args) {
    16. ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("test-async-%d").build();
    17. ExecutorService executor = new ThreadPoolExecutor(5, 10, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024),
    18. namedThreadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
    19. Callable task=() ->{
    20. MyUserDetails userDetails = (MyUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    21. String userAccount = userDetails.getUsername();
    22. return userAccount;
    23. };
    24. // 注意此时不能直接用executor.submit(task).get()方法去获取用户账号,这样也是会空指针异常的,而是需要用DelegatingSecuityContextCallable装饰一下原来的Callbale任务
    25. DelegatingSecurityContextCallable stringDelegatingSecurityContextCallable = new DelegatingSecurityContextCallable<>(task);
    26. try {
    27. String userAccount = executor.submit(stringDelegatingSecurityContextCallable).get();
    28. System.out.println(userAccount);
    29. } catch (InterruptedException e) {
    30. e.printStackTrace();
    31. } catch (ExecutionException e) {
    32. e.printStackTrace();
    33. }finally {
    34. executor.shutdown();
    35. }
    36. }
    37. }

    这里为了方便,所以我写在了main方法里边,在项目中,这个Callable任务对应的就是你的Service层的方法,在接口中用线程池调用的时候,就可以这样使用了。

    但是这种处理方式是从要被执行的任务方法本身进行修饰处理的,还有一种就是可以直接从线程池入手,使用DelegatingSecurityContextExecutorService来转发安全上下文。

    代码示例如下:

    1. public String test(){
    2. ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("test-async-%d").build();
    3. ExecutorService executor = new ThreadPoolExecutor(5, 10, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024),
    4. namedThreadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
    5. Callable task=() ->{
    6. MyUserDetails userDetails = (MyUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    7. String userAccount = userDetails.getUsername();
    8. return userAccount;
    9. };
    10. try {
    11. // 也可以通过修饰线程池的方式,来传播安全上下文
    12. executor=new DelegatingSecurityContextExecutorService(executor);
    13. String userAccount = executor.submit(task).get();
    14. System.out.println(userAccount);
    15. return userAccount;
    16. } catch (InterruptedException e) {
    17. e.printStackTrace();
    18. } catch (ExecutionException e) {
    19. e.printStackTrace();
    20. }finally {
    21. executor.shutdown();
    22. }
    23. return null;
    24. }

    而我们在日常项目中,使用CompletableFuture做异步处理也是很多的。所以,在使用CompletableFuture时,就需要指定一下自定义的线程池,而不能使用默认的线程池;

    示例代码如下:

    1. /**
    2. * @param taskObjectId
    3. * @description:
    4. * @author: xiaomifeng1010
    5. * @date:
    6. * @return:
    7. **/
    8. @ApiOperation(value = "测试获取详情")
    9. @GetMapping("/getIPOVisitObjectDetail")
    10. @ResponseBody
    11. public ApiResponse getDetail(@NotNull(message = "任务对象id为空") Long taskObjectId) {
    12. try {
    13. ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("visit-query-async-%d").build();
    14. int processors = Runtime.getRuntime().availableProcessors();
    15. log.info("当前cpu核心数:{}", processors);
    16. ExecutorService executor = new ThreadPoolExecutor(processors, 2 * processors + 1, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024),
    17. namedThreadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
    18. namedThreadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
    19. executor=new DelegatingSecurityContextExecutorService(executor);
    20. IpoVisitInfoDetailRespVO ipoVisitInfoDetailRespVO1 = CompletableFuture.supplyAsync(() -> ipoVisitInfoService.getIPOVisitObjectDetail(taskObjectId),executor)
    21. .thenApplyAsync(ipoVisitInfoDetailRespVO -> {
    22. List approveSendBackInfoList = ipoVisitInfoService.getApproveSendBackInfoList(taskObjectId);
    23. if (CollectionUtils.isNotEmpty(approveSendBackInfoList)) {
    24. ipoVisitInfoDetailRespVO.setApproveSendBackInfoList(approveSendBackInfoList);
    25. } else {
    26. ipoVisitInfoDetailRespVO.setApproveSendBackInfoList(Collections.emptyList());
    27. }
    28. return ipoVisitInfoDetailRespVO;
    29. },executor).get(5, TimeUnit.SECONDS);
    30. return ApiResult.success(ipoVisitInfoDetailRespVO1);
    31. } catch (InterruptedException | ExecutionException | TimeoutException ex ) {
    32. log.error("获取详情出错",ex);
    33. return ApiResponse.error("获取详情出错");
    34. }
    35. }

    所以如果你要在异步执行的线程方法中获取用户身份信息,需要传递安全上下文,就需要使用下边截图中CompletableFuture源码中的第二个重载方法,需要传入线程池,并且是被DelegatingSecurityContextExecutorService修饰的线程池。如果异步方法中不需要获取用户身份信息,则可以使用第一个重载方法,直接使用默认线程池就可以。 

     此外对于线程池的修饰类,还有一些其他的工具类

    去掉DelegatingSecurityContext前缀,就是这些类实现的对应JDK中的接口。比如 DelegatingSecurityContextExecutor就是实现了Executor接口,依次类比。

  • 相关阅读:
    servlet 教程 2:返回 jsp 页面
    LeetCode141.环形链表
    java面试题整理《基础篇》七
    mysql上课总结(3)(DML所有操作总结、TRUNCATE小结)
    java毕业设计恩施茶多芬网店系统设计与实现2021Mybatis+系统+数据库+调试部署
    Microsoft Releases .NET 7新功能
    C++中的继承
    JS实现瀑布流页面布局
    My Forty-eighth Page - 组合 - By Nicolas
    带你了解MySQL数据库(五)
  • 原文地址:https://blog.csdn.net/u011174699/article/details/127933955