1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Basic authentication with express

Posted at

nodeのexpressフレームワークでBasic認証を実現した場合。

認証関数を作成

app.js
var auth = express.basicAuth(function(user,pass){
	return user === myuser && pass === mypasswd;
});

routingのミドルウェアとして使用

app.get("/admin", auth, function(req, res){
	res.render("admin", { title : "This is admin" });
});

expressが使っているミドルウェア、Connectはroutingの際に、関数を何個も通ってレスポンスを行うという作りになっている。このときにfalsyな値を返すと次にいかないので、間にauth関数を挟んでやるとBasic認証の仕組みが実現できる。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?