Search code examples
springspring-securityaop

SecurityContextHolder.getContext() not working in AspectJ class


I created an @Aspect class and trying to get the principal object like..

SecurityContextHolder.getContext().getAuthentication() .getPrincipal()

inside my aspect class but I am getting null pointer. No context is available in my aspect.Any pointers.?


Solution

  • SecurityContextHolder associates a given SecurityContext with the current execution thread. As aspect intercepts method on separate thread(Not very sure), So you may need to change the security context holder strategy. As SecurityContextHolder provides a series of static methods that delegate to an instance of SecurityContextHolderStrategy. The purpose of SecurityContextHolder is to provide a convenient way to specify the strategy that should be used for a given JVM.

    If no strategy is defined SecurityContextHolder class will default to using MODE_THREADLOCAL.

    So you need to change the strategy to MODE_INHERITABLETHREADLOCAL.

    There are two ways to specify the desired strategy mode. The first is to specify it via the system property keyed on SYSTEM_PROPERTY. The second is to call setStrategyName(String) before using the class.

    In Spring, you need to define a bean in application context as follows:

    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetClass"><value>org.springframework.security.core.context.SecurityContextHolder</value></property>
        <property name="targetMethod"><value>setStrategyName</value></property>
        <property name="arguments">
            <list>
                <value>MODE_INHERITABLETHREADLOCAL</value>
            </list>
        </property>
    </bean>