Cloudflare Worker Template - Basic Auth
Christopher Talke Buscaino
In this post, we will walk through how to set up a Cloudflare Worker that protects your endpoint using Basic Authentication. This is a simple and effective way to restrict access to a specific part of your application by ensuring that only authorized users can access it.
What is Basic Authentication?
Basic Authentication is a method where a client sends a username and password to the server as part of the HTTP request header. This is typically used for securing APIs or other web services where you want to control access based on credentials. The credentials are base64 encoded and sent in the Authorization
header with the format: Basic <base64(username:password)>
.
Why Use Cloudflare Workers for Basic Authentication?
Sometimes you just need to quickly protect a route when you don't have the time to set up a proper authentication system. Cloudflare Workers provide a fast and simple way to add Basic Authentication, without the complexity of managing a full authentication backend. With Workers, you can immediately secure sensitive endpoints and ensure that only authorized users can access them, all while leveraging Cloudflare's network for speed and reliability.
How It Works
In the following code, we implement Basic Authentication to protect a Cloudflare Worker. If the client sends valid credentials, the worker will allow the request to go through and forward it to the original destination. If the credentials are missing or incorrect, the worker will respond with a 401 Unauthorized
message and prompt the client to provide the correct credentials.
Full Code Example
const expectedUsername = 'username'
const expectedPassword = 'password'
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const auth = request.headers.get('Authorization')
// If no auth header or invalid credentials, return 401
if (!auth || !isValidAuth(auth)) {
return new Response('Unauthorized - Please provide valid credentials', {
status: 401,
statusText: 'Unauthorized',
headers: {
'WWW-Authenticate': 'Basic realm="Secure Area"'
}
})
}
// If authenticated, forward the original request
return fetch(request)
}
function isValidAuth(auth) {
const [scheme, credentials] = auth.split(' ')
if (scheme !== 'Basic' || !credentials) {
return false
}
const decoded = atob(credentials)
const [username, password] = decoded.split(':')
return username === expectedUsername && password === expectedPassword
}
Code Breakdown
Authentication Check: The
Authorization
header is checked. If it's missing or the credentials are incorrect, the worker returns a401 Unauthorized
response. TheWWW-Authenticate
header in the response will prompt the client to send the correct credentials.Base64 Decoding: The provided credentials are base64 encoded, so we use the
atob()
function to decode them into a plain text string. This string is split intousername
andpassword
, which are then compared to the expected values.Forwarding the Request: If the user is authenticated, the worker forwards the original request using the
fetch()
function, allowing the request to proceed normally.
How to Customize
Change Username and Password: Simply update the values of
expectedUsername
andexpectedPassword
to your desired credentials.Apply to Your Endpoint: You can modify this worker to protect any endpoint. If you only want to protect certain routes, add logic to check the path and only apply authentication to those routes.
Use Case Scenarios
Private APIs: Protect an API with sensitive data by requiring authentication before any request is processed.
Internal Tools: Secure internal tools or services that you don't want accessible to the public without proper credentials.
Simple Authentication for Prototyping: For simple projects or prototypes, this approach gives a quick way to lock down your Cloudflare Worker endpoints without the need for more complex authentication solutions.
Conclusion
With Cloudflare Workers, you can easily add Basic Authentication to your endpoints to control access. The simplicity of this solution is perfect for scenarios where you need to add basic security with minimal overhead. If your project grows or you need more advanced authentication, you can explore additional solutions like OAuth or API keys. However, for many use cases, this worker template offers a lightweight and effective method to ensure only authorized users can access specific resources.