LoginSignup
7
8

More than 5 years have passed since last update.

Node-REDのhttp-inでBASIC認証(簡易版)

Posted at

要件

知らないアクセスを簡易的にはじきたくてBASIC認証を簡易的に使いたい。Custom Node node-red-contrib-httpauth もあるけれど、簡易的に実施したい場合。

Flow

basicAuth.png

 [{"id":"ed9fe57c.324f5","type":"http in","z":"7a0185dd.0a030c","name":"","url":"/autht","method":"get","swaggerDoc":"","x":176.5,"y":143.5,"wires":[["73231d07.6fbe64"]]},{"id":"a19a9fce.199a6","type":"http response","z":"7a0185dd.0a030c","name":"","x":504.5,"y":143,"wires":[]},{"id":"73231d07.6fbe64","type":"function","z":"7a0185dd.0a030c","name":"","func":"var auth = msg.req.get('Authorization');\n\nif(auth === undefined) { // 認証情報なし\n    msg.statusCode = 401;\n    msg.headers = {'WWW-Authenticate':'Basic realm=\\\"SECRET AREA\\\"'};\n    msg.payload = \"not auth\";\n}\nelse if (auth.indexOf('Basic ')===0) { // BASIC認証\n    msg.base64 = auth.slice(6);\n    if(msg.base64 === 'dXNlcjpwYXNzd29yZDEyMw==') { //echo -n 'user:password123' | base64 -e \n        msg.statusCode = 200;\n        msg.payload = 'logged in';\n    }\n    else { // 認証情報合ってない\n        msg.statusCode = 401;\n        msg.headers = {'WWW-Authenticate':'Basic realm=\\\"SECRET AREA\\\"'};\n        msg.payload = \"not auth\";\n    }\n}\nelse { // 違う認証方法だった \n    msg.statusCode = 401;\n    msg.headers = {'WWW-Authenticate':'Basic realm=\\\"SECRET AREA\\\"'};\n    msg.payload = \"not auth\";\n}\nreturn msg;","outputs":1,"noerr":0,"x":334.5,"y":143.5,"wires":[["a19a9fce.199a6","cf34f627.b61478"]]},{"id":"cf34f627.b61478","type":"debug","z":"7a0185dd.0a030c","name":"","active":true,"console":"false","complete":"base64","x":435.666748046875,"y":90.55555725097656,"wires":[]}] 

Function Nodeのコード

function
var auth = msg.req.get('Authorization');

if(auth === undefined) { // 認証情報なし
    msg.statusCode = 401;
    msg.headers = {'WWW-Authenticate':'Basic realm=\"SECRET AREA\"'};
    msg.payload = "not auth";
}
else if (auth.indexOf('Basic ')===0) { // BASIC認証
    msg.base64 = auth.slice(6);
    if(msg.base64 === 'dXNlcjpwYXNzd29yZDEyMw==') { //echo -n 'user:password123' | base64 -e 
        msg.statusCode = 200;
        msg.payload = 'logged in';
    }
    else { // 認証情報合ってない
        msg.statusCode = 401;
        msg.headers = {'WWW-Authenticate':'Basic realm=\"SECRET AREA\"'};
        msg.payload = "not auth";
    }
}
else { // 違う認証方法だった 
    msg.statusCode = 401;
    msg.headers = {'WWW-Authenticate':'Basic realm=\"SECRET AREA\"'};
    msg.payload = "not auth";
}
return msg;
7
8
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
7
8