Recipe Name:
Spring Security: race condition: SecurityContextHolder.getContext.setAuthentication
Description:
It is important to create a new SecurityContext instance to avoid race conditions across multiple threads.
Level:
error
Language:
  • java
Tags:
  • Spring
  • security
  • framework specific
  • web
  • Spring Security
Documentation

Reusing SecurityContext instances can lead to race conditions across multiple threads. To prevent this, consider using a fresh instance of SecurityContext.

Before
SecurityContextHolder.getContext.setAuthentication(authentication);
After
SecurityContext newContext = SecurityContextHolder.createEmptyContext();
newContext.setAuthentication(authentication);
Resources
Recipe
id: scw:spring:race-condition-SecurityContext
version: 10
metadata:
  name: 'Spring Security: race condition: SecurityContextHolder.getContext.setAuthentication'
  shortDescription: It is important to create a new SecurityContext instance to avoid race conditions across multiple threads.
  level: error
  language: java
  enabled: true
  comment: ""
  descriptionFile: descriptions/Spring_Security__race_condition__SecurityContextHolder.getContext.setAuthentication.html
  tags: Spring;security;framework specific;web;Spring Security
search:
  methodcall:
    name: setAuthentication
    declaration:
      type: org.springframework.security.core.context.SecurityContext
    "on":
      methodcall:
        name: getContext
        declaration:
          type: org.springframework.security.core.context.SecurityContextHolder
availableFixes:
- name: assign a new SecurityContext to the holder
  actions:
  - rewrite:
      to: |-
        org.springframework.security.core.context.SecurityContext newContext = org.springframework.security.core.context.SecurityContextHolder.createEmptyContext();
        newContext.setAuthentication({{{ arguments.0 }}});
        SecurityContextHolder.setContext(newContext)