LoginSignup
43
35

More than 3 years have passed since last update.

[node.js]node.js/expressでBASIC認証の実装

Last updated at Posted at 2018-03-18

概要

Herokuにデプロイしたアプリに認証をかけてみたかったのでやってみた。
Express + Node.jsを使ったアプリケーションに、BASIC認証を実装します。

環境

Node.js

v9.3.0

Express

v4.15.5

npm

v5.7.1

パッケージをインストールする

まず、basic-authパッケージをインストールします。

$ npm install basic-auth

実装

auth.jsを作成し、必要に応じてusernameとpasswordを変更します。

auth.js
const auth = require('basic-auth');

const admins = {
  'username': { password: 'password' },
};

module.exports = function (request, response, next) {
  const user = auth(request);
  if (!user || !admins[user.name] || admins[user.name].password !== user.pass) {
    response.set('WWW-Authenticate', 'Basic realm="example"');
    return response.status(401).send();
  }
  return next();
};

server.jsで呼び出します。

server.js
const auth = require('./auth');
const app = express();

app.use(auth);
43
35
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
43
35