As the jobs operate asynchronously they can't access to the user's session. A solution needs to be found so that that the jobs can access the user's session (if the user is still logged in at that moment).
User session
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
public class UserPrincipal implements UserDetails {
private User user;
private Collection<SimpleGrantedAuthority> grantedAuthorities;
public UserPrincipal(User user) {
Assert.notNull(user);
this.user = user;
Set<SimpleGrantedAuthority> authorities = new LinkedHashSet<>();
for (Role role : user.getRoles()) {
authorities.add(new SimpleGrantedAuthority(role.getName().toUpperCase(Locale.ENGLISH)));
}
grantedAuthorities = Collections.unmodifiableCollection(authorities);
}
}
Abstract Job class
public abstract class Job implements Runnable {
protected Logger logger = LoggerFactory.getLogger(getClass());
protected Job() {
}
@Override
public final void run() {
logger.debug("starting work");
/* code goes here */
logger.debug("work is done");
}
}
Job class
@Component
@Scope(value = "prototype")
public class ProcessLoggingJob extends Job {
@Override
protected void work(Map<String, Object> context) throws Exception {
// need to access user session here
}