🧪 Test CSRF Middleware

Test that your CSRF middleware is protecting your application.

🤔

Tests not working?

If you get stuck, contact us and our development team will work directly with you to get unblocked.

After implementing the signed double-submit cookie pattern, let's verify everything is working correctly. These basic tests will help ensure your CSRF middleware is properly protecting your application.


(Setup) Test Preparation

Similar to the testing of your auth middleware, ensure you have a test endpoint on your Express server available and a corresponding test component in your React frontend.


Implement Test Endpoint and Component

For this test, you will need a POST HTTP endpoint available as a test API implemented in your Express server that is protected by the CSRF middleware. It could be a simple API that just returns a 204 response.

// app.ts
import { authMiddleware, csrfMiddleware } from './middleware';

...

// Test POST endpoint
app.post('/test-post', [authMiddleware, csrfMiddleware], (req, res) => {
  return res.status(204).send();
});

...

In your React frontend, add a test component that makes the POST API request to your test endpoint.

// test-post-component.tsx
import axios from 'axios';

import { isForbidden, isUnauthorized, redirectToLogin } from '@/utils/helpers';

export function TestPostComponent() {
  const handleApiCall = async () => {
    try {
      const response = await axios.post(`<your-express-server-domain>/test-post`, { message: 'CSRF is great!' });
      alert('Success!');
    } catch (error: unknown) {
      if (isUnauthorized(error) || isForbidden(error)) {
        redirectToLogin();
      } else {
        console.error('Unexpected error:', error);
        alert('Something went wrong!'); 
      }
    }
  };

  return (
    <button onClick={handleApiCall}>
      Make API Call
    </button>
  );
}



1. Verify Successful Login

Verify that the CSRF middleware is not breaking the login flow.


Actions

  1. While on the Tenant Login Page, enter your test user's email and password.
  2. Click the "Log In" button.

Verify React Frontend Access

  • Verify that no errors occurred when submitting your credentials on the Tenant Login Page.
  • Verify that you land on the home route in your React frontend.
  • Verify that you have an application session cookie in your browser.
  • Verify that you have a CSRF cookie in you browser.

Network Request

Use your browser's developer tools to verify the Callback endpoint's response includes a Set-Cookie header for the CSRF Cookie.

CSRF Set-Cookie header

Browser Storage

Verify the CSRF Cookie appears in your browser's storage after the Set-Cookie header is sent. There may be browser extensions available to you for easier inspection of cookies for your Express server's domain.




2. Verify Protected Resource API - Success

Verify that the middleware protects your test API in your Express Server, similar to the Session endpoint.


Actions

  • After successfully logging into your application, click the button in your test component to trigger the POST API call to your test endpoint.

Verify Success

  • Verify that no errors occurred during the API call.

  • Verify that a success message is displayed in the UI.

  • Verify in the network requests in your browser that a 204 No Content HTTP response status was returned to your frontend.

  • Verify in the network requests that both the CSRF cookie and the CSRF header are present in the outgoing request to Express.

    CSRF in Outgoing Request



3. Verify Protected Resource API - Cookie Failure

Let's simulate a scenario where the CSRF cookie has been tampered with to trigger a 403 Forbidden HTTP response status from the CSRF middleware.


Actions

  • While still logged in to the application, manually delete the CSRF cookie from the browser.
  • Click the button in your test component to trigger the API call to your test endpoint.

Verify Login Redirect

  • Verify that the network requests show a 403 Forbidden HTTP response coming from your Express server's test endpoint.
  • Verify in the network requests that the browser redirects you to your Express server's Login endpoint.
  • Verify that you land on either the Tenant Discovery Page or the Tenant Login Page of your test tenant (depending on how you configured your domains).



4. Verify Protected Resource API - Header Failure

Let's simulate a scenario where the CSRF header has been tampered with to trigger a 403 Forbidden HTTP response status from the CSRF middleware.


Actions

  • Temporarily change the name of the CSRF header in your AJAX client code so that the header name doesn't match what the Express server expects to find. For example:

    // api-client.ts
    import axios from 'axios';
    
    const apiClient = axios.create({
      ...
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'I-AM-A-BAD-HEADER', // <-- Pick any bad value.
      ...
    });
    
    export { apiClient };
    
  • If logged out of the application, log back in with your test user.

  • Click the button in your test component to trigger the API call to your test endpoint.


Verify Login Redirect

  • Verify that the network requests show a 403 Forbidden HTTP response coming from your Express server's test endpoint.
  • Verify in the network requests that the browser redirects you to your Express server's Login endpoint.
  • Verify that you land on either the Tenant Discovery Page or the Tenant Login Page of your test tenant (depending on how you configured your domains).

❗️

Revert Your CSRF Header Name Code Change

Once this test is verified, undo the code change from above so that the CSRF header name value for your AJAX client has the proper value.




5. Verify CSRF Cookie Removal

Let's make sure the CSRF cookie gets removed from the browser on log out.


Actions

  • While still logged into your app, click the Logout button in your React frontend.

Verify Logout Behavior

  • Verify in the network requests that the browser redirects you to your Express server's Logout endpoint.
  • Verify that you land on either the Tenant Discovery Page or the Tenant Login Page of your test tenant (depending on how you configured your domains).
  • Verify in the network requests that you can see the Set-Cookie header with a the CSRF cookie in the response headers from Wristband's Logout endpoint. Also verify that the cookie was deleted successfully from the browser.

If all tests succeed, then CSRF protection has been successfully implemented. 🎉

Ultimate Defense

Well done. You've got the ultimate defense now.


One final auth step to cover: refreshing expired access tokens!