Skip to content

Instantly share code, notes, and snippets.

@kuzunoha-ne
Last active January 3, 2020 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuzunoha-ne/2d765944613e187f61f37523947517f2 to your computer and use it in GitHub Desktop.
Save kuzunoha-ne/2d765944613e187f61f37523947517f2 to your computer and use it in GitHub Desktop.
httpでBasicAuth
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