Protect Backend Endpoints
This guide walks you through implementing session validation to protect authenticated API endpoints.
Learn how to use .RequireWristbandSession() to protect API endpoints by requiring a valid authenticated session.
Protecting Endpoints from Unauthenticated Access
Add .RequireWristbandSession() to protect an endpoint from unauthenticated access.
// ProtectedRoutes.cs
using Wristband.AspNet.Auth;
public static class ProtectedEndpoints
{
public static WebApplication MapProtectedEndpoints(this WebApplication app)
{
app.MapGet("/api/protected-api", () =>
{
return Results.Ok(new { message = "This is a protected endpoint" });
})
.RequireWristbandSession();
return app;
}
}If a request is made without a valid session, the API returns a 401 Unauthorized response.
Handling 401 Responses in Frontend Code
When your frontend calls an API protected by .RequireWristbandSession(), it may receive:
401 Unauthorizedresponse when the user's session is missing or invalid.
Handle this response so users can recover from an expired or missing session. The following sections show common patterns for handling 401 Unauthorized responses in a JavaScript frontend.
Pattern 1: Use an Axios Interceptor
If you use Axios, create a response interceptor to handle 401 Unauthorized responses. The following example redirects the user to the Login Endpoint whenever a 401 Unauthorized response is received.
// api-client.ts
import axios from 'axios';
import { redirectToLogin } from '@wristband/react-client-auth';
const apiClient = axios.create({
baseURL: '<backend-apis-base-url>',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
withCredentials: true,
});
// If a 401 response is detected, redirect the user to your Login Endpoint.
const unauthorizedAccessInterceptor = (error: unknown) => {
if (axios.isAxiosError(error) && error.response?.status === 401) {
redirectToLogin('<your-login-endpoint-url>');
return;
}
return Promise.reject(error);
};
apiClient.interceptors.response.use(undefined, unauthorizedAccessInterceptor);
export { apiClient };
Pattern 2: Explicitly Catch Errors When Making API Calls
To handle 401 Unauthorized responses with more control, catch them directly when calling your backend APIs. This lets you implement custom error-handling logic for individual API calls.
import axios from 'axios';
import { redirectToLogin } from '@wristband/react-client-auth';
async function executeApiCall() {
try {
const response = await axios.get('<your-server-api-url>');
alert('Success!');
} catch (error: unknown) {
if (axios.isAxiosError(error) && error.response?.status === 401) {
redirectToLogin('<your-login-endpoint-url>');
} else {
console.error('Unexpected error:', error);
alert('Something went wrong!');
}
}
}
import { redirectToLogin } from '@wristband/react-client-auth';
function getCookie(name: string): string | null {
const match = document.cookie.match(new RegExp('(^|;\\s*)' + name + '=([^;]*)'));
return match ? decodeURIComponent(match[2]) : null;
}
async function executeApiCall() {
const csrfToken = getCookie('CSRF-TOKEN');
try {
const response = await fetch('/api/protected-endpoint', {
credentials: 'include',
headers: {
'X-CSRF-TOKEN': csrfToken ?? ''
}
});
if (!response.ok) {
if (response.status === 401 || response.status === 403) {
redirectToLogin('<your-login-endpoint-url>');
return;
}
const errorText = await response.text();
throw new Error(`HTTP error! status: ${response.status}, Message: ${errorText}`);
}
...
} catch (error) {
...
}
}Updated 12 days ago
What’s Next
Now that you've finished protecting your backend endpoints, let's run some final tests to ensure everything is working.