簡體   English   中英

保護特定路由node.js

[英]Securing a specific route node.js

嘿我正在使用Node.JS的基本身份驗證來保護路由。 我對Node.JS很陌生,並且不了解下一個函數在這種情況下的作用。 我要做的是確保路線: /admin/

注意:這是一個用於學習目的的項目,因此登錄部分不太嚴重,不會實時使用。

authentication.js

var basicAuth = require('basic-auth');

exports.BasicAuthentication = function(request, response, next) {

    function unauthorized(response) {
        response.set('WWW-Authenticate', 'Basic realm=Authorization Required');
        return response.send(401);
    };

    var user = basicAuth(request);

    if (!user || !user.name || !user.pass) {
        return unauthorized(response);
    };

    if (user.name === 'name' && user.pass === 'pass') {
        return next();
    } else {
        return unauthorized(response);
    };

};

和我導入模塊身份驗證的app.js:

app.get('/admin/', authentication.BasicAuthentication, function(req, res){
    console.log("hi u need to login");
});

所以我想要做的是在身份驗證通過時進一步路由用戶。

提前致謝!

嘗試:

app.get('/admin/', authentication.BasicAuthentication);
app.get('/admin/', function(req, res) {});

此功能稱為中間件:

var basicAuth = require('basic-auth');

exports.BasicAuthentication = function(request, response, next) {

    function unauthorized(response) {
        response.set('WWW-Authenticate', 'Basic realm=Authorization Required');
        return response.send(401);
    };

    var user = basicAuth(request);

    if (!user || !user.name || !user.pass) {
        return unauthorized(response);
    };

    if (user.name === 'name' && user.pass === 'pass') {
        return next();
    } else {
        return unauthorized(response);
    };

};

中間件是一個可以為各種目的定義的函數:

  1. 使用中間件
  2. 寫一個中間件

一種簡單的方法是在執行另一個動作之前運行的功能,一個通用的目的是保護某些路由以進行未授權的訪問。

您可以保護私有路由,然后調用authentication.BasicAuthentication before function(req,res){}

一些例子:

app.get('/user-profile/', authentication.BasicAuthentication, function(req, res){
    //private info
});

app.get('/foo/', function(req, res){
    //public info
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM