Last active
January 3, 2020 10:12
-
-
Save kuzunoha-ne/2d765944613e187f61f37523947517f2 to your computer and use it in GitHub Desktop.
httpでBasicAuth
This file contains 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
import http from 'http'; | |
import { Buffer } from 'buffer'; | |
const server = http.createServer(); | |
server.on('request', (req:http.IncomingMessage, res:http.ServerResponse) => { | |
if(req.headers.authorization) { // req.headers.authorization = "Basic a3V6dW5vaGE6YWFh" | |
const encodedPass = req.headers.authorization.split(' ')[1]; // encodedPass = "a3V6dW5vaGE6YWFh" | |
const decodePass = Buffer.from(encodedPass, 'base64').toString('utf8'); // decodedPass = "kuzunoha:hogehoge" | |
const auth = {username:decodePass.split(':')[0], password:decodePass.split(':')[1]}; // auth = {username:kuzunoha, password:hogehoge} | |
if(auth.username == 'kuzunoha' && auth.password == 'hogehoge'){ | |
res.writeHead(200, {'Content-Type':'text/plain', 'Accept-Charset':'utf-8'}); | |
res.end('success\n'); | |
return; | |
} | |
} | |
res.writeHead(401, {'Content-Type':'text/plain', 'Accept-Charset':'utf-8', 'WWW-Authenticate': `Basic realm="Enter username and password."`}); | |
res.end('401 not authenticated\n'); | |
return; | |
}); | |
server.listen(9000, ()=>{ | |
console.log('listen http://127.0.0.1:9000\n'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment