Remote Authentication

In order to avoid customers' resources being accessed by illegal users, this example transmits the request to the customer-specified remote authentication server. The authentication server verifies the user's request, and the Edge Functions decide whether to allow access to the target resources based on the check result returned by the remote authentication server. If the authentication fails, the client will be responded with a 403 status code.

Sample Code

async function handleRequest(request) {
  // Remote authentication API address
  const checkAuthUrl = 'https://www.example.com/';
  // Initiate remote authentication
  const checkAuthRes = await fetch(checkAuthUrl);

  // Authentication passed, normal access to resources
  if (checkAuthRes.status === 200) {
    return fetch(request, {
      headers: request.headers,
    });
  }
  
  // Authentication failed, prohibit access to resources
  return new Response(null, {
    status: 403
  });
}

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

Example preview

Enter the URL that matches the triggering rules of the Edge Functions in the address bar of the browser on both PC and mobile (https://example.com/app/index.html) to preview the example effect.

  1. Authentication passed, normal access to resources.

19.1.png

  1. Authentication failed, prohibit access to resources.

19.2.png

Related references

  1. Runtime APIs: Fetch
  2. Runtime APIs: Response