Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.?

like image 407
Vikram Avatar asked Nov 01 '25 23:11

Vikram


2 Answers

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>
like image 56
VirtualLogic Avatar answered Nov 04 '25 17:11

VirtualLogic


This could happen in case the aspect is executed...

  1. ...on a non-servlet thread, i.e. some background thread or one that has been started during request processing. In the latter case you can solve the problem by configuring the SecurityContextHolder to store the context in an inheritable ThreadLocal which spawned threads can access as well (see the javadoc for details).

  2. ...before the request gets authenticated by the responsible security filters. Enable logging for security classes, or set up some breakpoints for a debug session to check if this is the problem.

like image 42
zagyi Avatar answered Nov 04 '25 19:11

zagyi