Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save miensol/06a6e7422935b553b62438a06661f93b to your computer and use it in GitHub Desktop.
Save miensol/06a6e7422935b553b62438a06661f93b to your computer and use it in GitHub Desktop.
import org.springframework.core.task.TaskExecutor
import org.springframework.security.core.Authentication
import org.springframework.security.core.context.SecurityContext
import org.springframework.security.core.context.SecurityContextHolder
class SecurityContextHolderAwareTaskExecutor(private val realTaskExecutor: TaskExecutor) : TaskExecutor {
override fun execute(task: Runnable) {
val context = SecurityContextHolder.getContext()
if (context != null) {
realTaskExecutor.execute(WrappingRunnable(task, context))
} else {
realTaskExecutor.execute(task)
}
}
class WrappingRunnable(val innerTask: Runnable, val contextToSet: SecurityContext) : Runnable {
override fun run() {
try {
SecurityContextHolder.setContext(contextToSet)
innerTask.run()
} finally {
SecurityContextHolder.clearContext()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment