Skip to content

Refactor Spring utilities to avoid static access to SecurityContextHolder #21401

@mcollovati

Description

@mcollovati

Describe your motivation

A couple of Vaadin spring utility classes are using the static SecurityContextHolder.getContext() method to get the Spring security context.
That method relies on a SecurityContextHolderStrategy that is statically set based on system properties or calling static methods on the SecurityContextHolder class.

Vaadin provides a custom strategy (VaadinAwareSecurityContextHolderStrategy) built on top of VaadinSession with a fallback to thread local.
However, since Vaadin utilities are using SecurityContextHolder.getContext(), it is required to eagerly set the instance as a global strategy using the workaround present in VaadinAwareSecurityContextHolderStrategyConfiguration

   @Bean(name = "VaadinSecurityContextHolderStrategy")
    @ConditionalOnMissingBean
    public VaadinAwareSecurityContextHolderStrategy securityContextHolderStrategy() {
        VaadinAwareSecurityContextHolderStrategy vaadinAwareSecurityContextHolderStrategy = new VaadinAwareSecurityContextHolderStrategy();
        // Use a security context holder that can find the context from Vaadin
        // specific classes
        SecurityContextHolder.setContextHolderStrategy(
                vaadinAwareSecurityContextHolderStrategy);
        return vaadinAwareSecurityContextHolderStrategy;
    }

This is not optimal, especially with the new VaadinSecurityConfigurer because it requires the developer to import the VaadinAwareSecurityContextHolderStrategyConfiguration into the application security configuration class.(VaadinWebSecurity already does it).
In addition, Spring recommends wiring the strategy into other components instead of accessing the static method.

Describe the solution you'd like

Make sure that Vaadin spring utilities use an injected SecurityContextHolderStrategy bean instead of invoking static access methods in SecurityContextHolder.

Describe alternatives you've considered

The current alternative is the workaround in VaadinAwareSecurityContextHolderStrategyConfiguration

Additional context

spring-projects/spring-security#10973
spring-projects/spring-security#11886
spring-projects/spring-security#12561

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Status

    Inbox (needs triage)

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions