Spring Security: What is the right way to call method secured with @PreAuthorize in background task?

You can register an Authentication token yourself in the current thread and session(if used in a web application):

SecurityContextHolder.getContext().setAuthentication(token);
session.put(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());

You can use the standard UsernamePasswordAuthenticationToken for this as long as you add the appropriate roles.


In this case Manual Workaround is an option:

(1) If this is an independent job,

Create an Authentication object and set it to the security context before the secured method is invoked. Remove the Authentication object from the security context after the secured method is done execution.

public final class AuthenticationUtil {

//Ensures that this class cannot be instantiated
private AuthenticationUtil() {
}

public static void clearAuthentication() {
    SecurityContextHolder.getContext().setAuthentication(null);
}

public static void configureAuthentication(String role) {
    Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(role);
    Authentication authentication = new UsernamePasswordAuthenticationToken(
            "user",
            role,
            authorities
    );
    SecurityContextHolder.getContext().setAuthentication(authentication);
}

So it would look like

AuthenticationUtil.configureAuthentication(role);
// Call to the secured method 
AuthenticationUtil.clearAuthentication();

(2) For web application, where we can't make authentication object as null, don't call

AuthenticationUtil.configureAuthentication(role);
// call to the secured method