spring-security/docs/modules/ROOT/pages/servlet/integrations/servlet-api.adoc

278 lines
11 KiB
Plaintext

[[servletapi]]
= Servlet API integration
This section describes how Spring Security is integrated with the Servlet API.
[[servletapi-25]]
== Servlet 2.5+ Integration
This section describes how Spring Security integrates with the Servlet 2.5 specification.
[[servletapi-remote-user]]
=== HttpServletRequest.getRemoteUser()
https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()[`HttpServletRequest.getRemoteUser()`] returns the result of `SecurityContextHolder.getContext().getAuthentication().getName()`, which is typically the current username.This can be useful if you want to display the current username in your application.
Additionally, you can check this for null to determine whether a user has authenticated or is anonymous.
Knowing whether the user is authenticated or not can be useful for determining if certain UI elements should be shown or not (for example, a logout link that should be displayed only if the user is authenticated).
[[servletapi-user-principal]]
=== HttpServletRequest.getUserPrincipal()
https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()[`HttpServletRequest.getUserPrincipal()`] returns the result of `SecurityContextHolder.getContext().getAuthentication()`.
This means that it is an `Authentication`, which is typically an instance of `UsernamePasswordAuthenticationToken` when using username- and password-based authentication.
This can be useful if you need additional information about your user.
For example, you might have created a custom `UserDetailsService` that returns a custom `UserDetails` containing a first and last name for your user.
You could obtain this information with the following:
====
.Java
[source,java,role="primary"]
----
Authentication auth = httpServletRequest.getUserPrincipal();
// assume integrated custom UserDetails called MyCustomUserDetails
// by default, typically instance of UserDetails
MyCustomUserDetails userDetails = (MyCustomUserDetails) auth.getPrincipal();
String firstName = userDetails.getFirstName();
String lastName = userDetails.getLastName();
----
.Kotlin
[source,kotlin,role="secondary"]
----
val auth: Authentication = httpServletRequest.getUserPrincipal()
// assume integrated custom UserDetails called MyCustomUserDetails
// by default, typically instance of UserDetails
val userDetails: MyCustomUserDetails = auth.principal as MyCustomUserDetails
val firstName: String = userDetails.firstName
val lastName: String = userDetails.lastName
----
====
[NOTE]
====
It should be noted that it is typically bad practice to perform so much logic throughout your application.
Instead, one should centralize it to reduce any coupling of Spring Security and the Servlet API's.
====
[[servletapi-user-in-role]]
=== HttpServletRequest.isUserInRole(String)
https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)[`HttpServletRequest.isUserInRole(String)`] determines if `SecurityContextHolder.getContext().getAuthentication().getAuthorities()` contains a `GrantedAuthority` with the role passed into `isUserInRole(String)`.
Typically, users should not pass the `ROLE_` prefix to this method, since it is added automatically.
For example, if you want to determine if the current user has the authority "ROLE_ADMIN", you could use the following:
====
.Java
[source,java,role="primary"]
----
boolean isAdmin = httpServletRequest.isUserInRole("ADMIN");
----
.Kotlin
[source,kotlin,role="secondary"]
----
val isAdmin: Boolean = httpServletRequest.isUserInRole("ADMIN")
----
====
This might be useful to determine if certain UI components should be displayed.
For example, you might display admin links only if the current user is an admin.
[[servletapi-3]]
== Servlet 3+ Integration
The following section describes the Servlet 3 methods with which Spring Security integrates.
[[servletapi-authenticate]]
=== HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse)
You can use the https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#authenticate%28javax.servlet.http.HttpServletResponse%29[`HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse)`] method to ensure that a user is authenticated.
If they are not authenticated, the configured `AuthenticationEntryPoint` is used to request the user to authenticate (redirect to the login page).
[[servletapi-login]]
=== HttpServletRequest.login(String,String)
You can use the https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login%28java.lang.String,%20java.lang.String%29[`HttpServletRequest.login(String,String)`] method to authenticate the user with the current `AuthenticationManager`.
For example, the following would attempt to authenticate with a username of `user` and a password of `password`:
====
.Java
[source,java,role="primary"]
----
try {
httpServletRequest.login("user","password");
} catch(ServletException ex) {
// fail to authenticate
}
----
.Kotlin
[source,kotlin,role="secondary"]
----
try {
httpServletRequest.login("user", "password")
} catch (ex: ServletException) {
// fail to authenticate
}
----
====
[NOTE]
====
You need not catch the `ServletException` if you want Spring Security to process the failed authentication attempt.
====
[[servletapi-logout]]
=== HttpServletRequest.logout()
You can use the https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout%28%29[`HttpServletRequest.logout()`] method to log out the current user.
Typically, this means that the `SecurityContextHolder` is cleared out, the `HttpSession` is invalidated, any "`Remember Me`" authentication is cleaned up, and so on.
However, the configured `LogoutHandler` implementations vary, depending on your Spring Security configuration.
Note that, after `HttpServletRequest.logout()` has been invoked, you are still in charge of writing out a response.
Typically, this would involve a redirect to the welcome page.
[[servletapi-start-runnable]]
=== AsyncContext.start(Runnable)
The https://docs.oracle.com/javaee/6/api/javax/servlet/AsyncContext.html#start%28java.lang.Runnable%29[`AsyncContext.start(Runnable)`] method ensures your credentials are propagated to the new `Thread`.
By using Spring Security's concurrency support, Spring Security overrides `AsyncContext.start(Runnable)` to ensure that the current `SecurityContext` is used when processing the Runnable.
The following example outputs the current user's Authentication:
====
.Java
[source,java,role="primary"]
----
final AsyncContext async = httpServletRequest.startAsync();
async.start(new Runnable() {
public void run() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
try {
final HttpServletResponse asyncResponse = (HttpServletResponse) async.getResponse();
asyncResponse.setStatus(HttpServletResponse.SC_OK);
asyncResponse.getWriter().write(String.valueOf(authentication));
async.complete();
} catch(Exception ex) {
throw new RuntimeException(ex);
}
}
});
----
.Kotlin
[source,kotlin,role="secondary"]
----
val async: AsyncContext = httpServletRequest.startAsync()
async.start {
val authentication: Authentication = SecurityContextHolder.getContext().authentication
try {
val asyncResponse = async.response as HttpServletResponse
asyncResponse.status = HttpServletResponse.SC_OK
asyncResponse.writer.write(String.valueOf(authentication))
async.complete()
} catch (ex: Exception) {
throw RuntimeException(ex)
}
}
----
====
[[servletapi-async]]
=== Async Servlet Support
If you use Java-based configuration, you are ready to go.
If you use XML configuration, a few updates are necessary.
The first step is to ensure that you have updated your `web.xml` file to use at least the 3.0 schema:
====
[source,xml]
----
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
</web-app>
----
====
Next, you need to ensure that your `springSecurityFilterChain` is set up for processing asynchronous requests:
====
[source,xml]
----
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
<async-supported>true</async-supported>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ASYNC</dispatcher>
</filter-mapping>
----
====
Now Spring Security ensures that your `SecurityContext` is propagated on asynchronous requests, too.
So how does it work? If you are not really interested, feel free to skip the remainder of this section
Most of this is built into the Servlet specification, but there is a little bit of tweaking that Spring Security does to ensure things work properly with asynchronous requests.
Prior to Spring Security 3.2, the `SecurityContext` from the `SecurityContextHolder` was automatically saved as soon as the `HttpServletResponse` was committed.
This can cause issues in an asynchronous environment.
Consider the following example:
====
.Java
[source,java,role="primary"]
----
httpServletRequest.startAsync();
new Thread("AsyncThread") {
@Override
public void run() {
try {
// Do work
TimeUnit.SECONDS.sleep(1);
// Write to and commit the httpServletResponse
httpServletResponse.getOutputStream().flush();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}.start();
----
.Kotlin
[source,kotlin,role="secondary"]
----
httpServletRequest.startAsync()
object : Thread("AsyncThread") {
override fun run() {
try {
// Do work
TimeUnit.SECONDS.sleep(1)
// Write to and commit the httpServletResponse
httpServletResponse.outputStream.flush()
} catch (ex: java.lang.Exception) {
ex.printStackTrace()
}
}
}.start()
----
====
The issue is that this `Thread` is not known to Spring Security, so the `SecurityContext` is not propagated to it.
This means that, when we commit the `HttpServletResponse`, there is no `SecurityContext`.
When Spring Security automatically saved the `SecurityContext` on committing the `HttpServletResponse`, it would lose a logged in user.
Since version 3.2, Spring Security is smart enough to no longer automatically save the `SecurityContext` on committing the `HttpServletResponse` as soon as `HttpServletRequest.startAsync()` is invoked.
[[servletapi-31]]
== Servlet 3.1+ Integration
The following section describes the Servlet 3.1 methods that Spring Security integrates with.
[[servletapi-change-session-id]]
=== HttpServletRequest#changeSessionId()
https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html#changeSessionId()[HttpServletRequest.changeSessionId()] is the default method for protecting against xref:servlet/authentication/session-management.adoc#ns-session-fixation[Session Fixation] attacks in Servlet 3.1 and higher.