Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/modules/ROOT/nav.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
*** xref:features/integrations/cryptography.adoc[Cryptography]
*** xref:features/integrations/data.adoc[Spring Data]
*** xref:features/integrations/concurrency.adoc[Java's Concurrency APIs]
*** xref:features/integrations/outside-servlet.adoc[Outside a Servlet Request]
*** xref:features/integrations/jackson.adoc[Jackson]
*** xref:features/integrations/localization.adoc[Localization]
* xref:modules.adoc[Project Modules]
Expand Down
33 changes: 33 additions & 0 deletions docs/modules/ROOT/pages/features/integrations/outside-servlet.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
[[outside-servlet]]
= Using Spring Security Outside a Servlet Request

Outside the servlet filter chain, Spring Security does not automatically establish a
`SecurityContext` for the current execution.
If secured code needs an `Authentication` in these environments, the application can
establish and clear a `SecurityContext` explicitly.

For example, one possible pattern is:

[source,java]
----
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication); // <1>
SecurityContextHolder.setContext(context);
try {
// invoke secured service
} finally {
SecurityContextHolder.clearContext();
}
----
<1> How the `Authentication` is created depends on the application.
For example, it may come from an application-specific authentication flow
or another authentication mechanism.

The same general pattern can apply to scheduled jobs, command-line runners, and message handlers,
depending on how the application authenticates the work being performed.

For propagating the `SecurityContext` across thread boundaries, see
xref:features/integrations/concurrency.adoc[Java's Concurrency APIs].

For Spring Security test support, including annotations such as `@WithMockUser`,
see xref:servlet/test/method.adoc[Testing Method Security].