Remote Authentication

In this example, an Edge Function is used to implement remote authentication. 

If it is a legitimate user, the verification passes and access to resources is allowed to continue; if it is an illegitimate user, the verification fails and an exception response is returned.

Code

const AUTH_URL = 'https://data.playground.edgeone.ai/api/user';

async function handleRequest(request) {
  const userId = request.headers.get('x-user-id');
  
  const response = await fetch(`${AUTH_URL}/${userId}`);
  
  if (response.status === 200) {
    return new Response('Valid user');
  }
  
  return new Response('Invalid user', {
    status: response.status
  });
}

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

Preview

If authentication fails, access is denied.

Xnip2024-07-15_17-30-19.png

If authentication is successful, access is allowed.

Xnip2024-07-15_17-30-02.png

References