Class DSpaceCsrfTokenRepository

java.lang.Object
org.dspace.app.rest.security.DSpaceCsrfTokenRepository
All Implemented Interfaces:
CsrfTokenRepository

public class DSpaceCsrfTokenRepository extends Object implements CsrfTokenRepository
This is a custom Spring Security CsrfTokenRepository which supports *cross-domain* CSRF protection (allowing the client and backend to be on different domains). It's inspired by https://stackoverflow.com/a/33175322

This is essentially a customization of Spring Security's CookieCsrfTokenRepository: https://github.com/spring-projects/spring-security/blob/6.2.x/web/src/main/java/org/springframework/security/web/csrf/CookieCsrfTokenRepository.java However, as that class is "final" we aannot override it directly.

How it works: 1. Backend generates XSRF token & stores in a *server-side* cookie named DSPACE-XSRF-COOKIE. By default, this cookie is not readable to JS clients (HttpOnly=true). But, it is returned (by user's browser) on every subsequent request to backend. See "saveToken()" method below. 2. At the same time, backend also sends the generated XSRF token in a header named DSPACE-XSRF-TOKEN to client. See "saveToken()" method below. 3. Client MUST look for DSPACE-XSRF-TOKEN header in a response from backend. If found, the client MUST store/save this token for later request(s). For Angular UI, this task is performed by the XsrfInterceptor. 4. Whenever the client is making a mutating request (e.g. POST, PUT, DELETE, etc), the XSRF token is REQUIRED to be sent back in the X-XSRF-TOKEN header. * NOTE: non-mutating requests (e.g. GET, HEAD) do not check for an XSRF token. This is default behavior in Spring Security 5. On backend, the X-XSRF-TOKEN header is received & compared to the current value of the *server-side* cookie named DSPACE-XSRF-COOKIE. If tokens match, the request is accepted. If tokens don't match a 403 is returned. This is done automatically by Spring Security. In summary, the XSRF token is ALWAYS sent to/from the client & backend via *headers*. This is what allows the client and backend to be on different domains. The server-side cookie named DSPACE-XSRF-COOKIE is (usually) not accessible to the client. It only exists to allow the server-side to remember the currently active XSRF token, so that it can validate the token sent (by the client) in the X-XSRF-TOKEN header.