Skip to content

Instantly share code, notes, and snippets.

@myl7
Created January 8, 2021 22:30
Show Gist options
  • Save myl7/311a2b303ba39d47fc8ed443e2db234e to your computer and use it in GitHub Desktop.
Save myl7/311a2b303ba39d47fc8ed443e2db234e to your computer and use it in GitHub Desktop.
Cloudflare worker HTTP basic auth
addEventListener('fetch', e => {
e.respondWith(handleReq(e.request))
})
const handleReq = async (req) => {
if (!req.headers.has('Authorization')) {
return new Response(null, {
status: 401,
headers: {'WWW-Authenticate': 'Basic realm="mylmoe admin secret"'}
})
}
const auth = req.headers.get('Authorization')
if (auth.substring(0, 6) !== 'Basic ') {
return new Response(null, {status: 403})
}
let secret = null
try {
secret = atob(auth.substring(6))
} catch (e) {
return new Response(null, {status: 403})
}
if (secret !== SECRET) {
return new Response(null, {status: 403})
}
const body = await req.json()
return new Response(JSON.stringify(body), {status: 200})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment