Created
January 8, 2021 22:30
-
-
Save myl7/311a2b303ba39d47fc8ed443e2db234e to your computer and use it in GitHub Desktop.
Cloudflare worker HTTP basic auth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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