Class DSpaceCsrfAuthenticationStrategy

java.lang.Object
org.dspace.app.rest.security.DSpaceCsrfAuthenticationStrategy
All Implemented Interfaces:
SessionAuthenticationStrategy

public class DSpaceCsrfAuthenticationStrategy extends Object implements SessionAuthenticationStrategy
Custom SessionAuthenticationStrategy to be used alongside DSpaceCsrfTokenRepository.

Because DSpace is Stateless, this class only resets the CSRF Token if the client has attempted to use it (either successfully or unsuccessfully). This ensures that the Token is not changed on every request (since we are stateless every request creates a new Authentication object).

This is essentially a customization of Spring Security's CsrfAuthenticationStrategy: https://github.com/spring-projects/spring-security/blob/6.2.x/web/src/main/java/org/springframework/security/web/csrf/CsrfAuthenticationStrategy.java

  • Constructor Details

    • DSpaceCsrfAuthenticationStrategy

      public DSpaceCsrfAuthenticationStrategy(CsrfTokenRepository tokenRepository)
      Creates a new instance
      Parameters:
      tokenRepository - the CsrfTokenRepository to use
  • Method Details

    • setRequestHandler

      public void setRequestHandler(CsrfTokenRequestHandler requestHandler)
    • onAuthentication

      public void onAuthentication(Authentication authentication, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws SessionAuthenticationException
      This method is triggered anytime a new Authentication occurs. As DSpace uses Stateless authentication, this method is triggered on _every request_ after an initial login occurs. This is because the Spring Security 'Authentication' object is recreated on every request.

      Therefore, for DSpace, we've customized this method to ensure a new CSRF Token is NOT generated each time a new Authentication object is created -- as doing so causes the CSRF Token to change with every request. Instead, we check to see if the client also passed a CSRF token via a querystring parameter (i.e. "_csrf"). If so, this means the client has sent the token in a less secure manner & it must then be regenerated.

      NOTE: We also automatically regenerate CSRF token on login/logout via JWTTokenRestAuthenticationServiceImpl.

      Specified by:
      onAuthentication in interface SessionAuthenticationStrategy
      Throws:
      SessionAuthenticationException
    • resetCSRFToken

      public void resetCSRFToken(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response)
      A custom utility method to force Spring Security to reset the CSRF token. This is used by DSpace to reset the token whenever the CSRF token is passed insecurely (as a request param, see onAuthentication() above) or on logout (see JWTTokenRestAuthenticationServiceImpl)
      Parameters:
      request - current HTTP request
      response - current HTTP response
      See Also: