programing

Node와 Express 4를 이용한 기본 HTTP 인증

codeshow 2023. 9. 14. 23:45
반응형

Node와 Express 4를 이용한 기본 HTTP 인증

Express v3로 기본 HTTP 인증을 구현하는 것은 사소한 일인 것 같습니다.

app.use(express.basicAuth('username', 'password'));

버전 4(4.2를 사용하고 있습니다)가 제거되었습니다.basicAuth미들웨어라 좀 막혔어요나는 다음 코드를 가지고 있지만 브라우저가 사용자에게 자격 증명을 요구하는 것을 야기하지는 않습니다. 이것은 내가 원하는 것(그리고 이전 방법이 했다고 생각하는 것)입니다.)

app.use(function(req, res, next) {
    var user = auth(req);

    if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
        res.writeHead(401, 'Access invalid for user', {'Content-Type' : 'text/plain'});
        res.end('Invalid credentials');
    } else {
        next();
    }
});

바닐라 자바스크립트(ES6)를 사용한 심플 베이직 인증

app.use((req, res, next) => {

  // -----------------------------------------------------------------------
  // authentication middleware

  const auth = {login: 'yourlogin', password: 'yourpassword'} // change this

  // parse login and password from headers
  const b64auth = (req.headers.authorization || '').split(' ')[1] || ''
  const [login, password] = Buffer.from(b64auth, 'base64').toString().split(':')

  // Verify login and password are set and correct
  if (login && password && login === auth.login && password === auth.password) {
    // Access granted...
    return next()
  }

  // Access denied...
  res.set('WWW-Authenticate', 'Basic realm="401"') // change this
  res.status(401).send('Authentication required.') // custom message

  // -----------------------------------------------------------------------

})

참고: 이 "미들웨어"는 모든 핸들러에서 사용할 수 있습니다.제거만 하면 됩니다.next()논리를 뒤집는 겁니다아래의 1-문 예 또는 이 답변의 편집 이력을 참조하십시오.

왜요?

  • req.headers.authorization값을 포함합니다. "Basic <base64 string>", 하지만 비울 수도 있고 실패하는 것을 원하지 않기 때문에 이상한 조합은|| ''
  • 노드는 모릅니다.atob()그리고.btoa(), 그 때문에

ES6 -> ES5

const 정당합니다var.. 모종의
(x, y) => {...} 정당합니다function(x, y) {...}
const [login, password] = ...split() 단 둘입니다.var과제를 일괄적으로

영감의 출처(패키지 사용)


The above is a 초간단의 example that was intended to be 초단발의 and quickly deployable to your playground server. But as was pointed out in the comments, passwords can also contain colon characters :. To correctly extract it from the b64auth, you can use this.

  // parse login and password from headers
  const b64auth = (req.headers.authorization || '').split(' ')[1] || ''
  const strauth = Buffer.from(b64auth, 'base64').toString()
  const splitIndex = strauth.indexOf(':')
  const login = strauth.substring(0, splitIndex)
  const password = strauth.substring(splitIndex + 1)

  // using shorter regex by @adabru
  // const [_, login, password] = strauth.match(/(.*?):(.*)/) || []

하나의 문에서 기본 인증

...한편, 로그인을 한 번만 사용하거나 아주 적은 로그인만 사용하는 경우, 필요한 최소한의 값입니다. (자격 증명을 구문 분석할 필요도 전혀 없습니다.)

function (req, res) {
//btoa('yourlogin:yourpassword') -> "eW91cmxvZ2luOnlvdXJwYXNzd29yZA=="
//btoa('otherlogin:otherpassword') -> "b3RoZXJsb2dpbjpvdGhlcnBhc3N3b3Jk"

  // Verify credentials
  if (  req.headers.authorization !== 'Basic eW91cmxvZ2luOnlvdXJwYXNzd29yZA=='
     && req.headers.authorization !== 'Basic b3RoZXJsb2dpbjpvdGhlcnBhc3N3b3Jk')        
    return res.status(401).send('Authentication required.') // Access denied.   

  // Access granted...
  res.send('hello world')
  // or call next() if you use it as middleware (as snippet #1)
}

추신: "보안" 경로와 "공공" 경로가 모두 있어야 합니까?대신에 사용하는 것을 고려해 보십시오.

var securedRoutes = require('express').Router()

securedRoutes.use(/* auth-middleware from above */)
securedRoutes.get('path1', /* ... */) 

app.use('/secure', securedRoutes)
app.get('public', /* ... */)

// example.com/public       // no-auth
// example.com/secure/path1 // requires auth

TL;DR:

express.basicAuth사라졌습니다
basic-auth-connect사용하지 않습니다.
basic-auth논리가 전혀 없습니다
http-auth오버킬입니다.
express-basic-auth당신이 원하는 것입니다.

자세한 정보:

Express를 사용하고 있으니 사용하시면 됩니다.express-basic-auth미들웨어

문서 참조:

예:

const app = require('express')();
const basicAuth = require('express-basic-auth');
 
app.use(basicAuth({
    users: { admin: 'supersecret123' },
    challenge: true // <--- needed to actually show the login dialog!
}));

많은 미들웨어가 v4의 Express 코어에서 꺼내져 별도의 모듈에 삽입되었습니다.기본 인증 모듈은 다음과 같습니다. https://github.com/expressjs/basic-auth-connect

이 예제는 다음과 같이 변경하면 됩니다.

var basicAuth = require('basic-auth-connect');
app.use(basicAuth('username', 'password'));

정답을 찾기 위해 원본 코드를 사용했습니다.

app.use(function(req, res, next) {
    var user = auth(req);

    if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
        res.statusCode = 401;
        res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
        res.end('Unauthorized');
    } else {
        next();
    }
});

express 4.0에서 http-auth로 기본 인증을 변경했는데 코드는 다음과 같습니다.

var auth = require('http-auth');

var basic = auth.basic({
        realm: "Web."
    }, function (username, password, callback) { // Custom authentication method.
        callback(username === "userName" && password === "password");
    }
);

app.get('/the_url', auth.connect(basic), routes.theRoute);

이를 위한 모듈이 여러 개 있는 것 같고, 일부는 사용하지 않는 모듈도 있습니다.

활성 상태로 보입니다.
https://github.com/jshttp/basic-auth

사용 예는 다음과 같습니다.

// auth.js

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

var admins = {
  'art@vandelay-ind.org': { password: 'pa$$w0rd!' },
};


module.exports = function(req, res, next) {

  var user = auth(req);
  if (!user || !admins[user.name] || admins[user.name].password !== user.pass) {
    res.set('WWW-Authenticate', 'Basic realm="example"');
    return res.status(401).send();
  }
  return next();
};




// app.js

var auth = require('./auth');
var express = require('express');

var app = express();

// ... some not authenticated middlewares

app.use(auth);

// ... some authenticated middlewares

당신이 그들을.auth미들웨어는 정확한 위치에 있습니다. 그 이전의 미들웨어는 인증되지 않습니다.

function auth (req, res, next) {
  console.log(req.headers);
  var authHeader = req.headers.authorization;
  if (!authHeader) {
      var err = new Error('You are not authenticated!');
      res.setHeader('WWW-Authenticate', 'Basic');
      err.status = 401;
      next(err);
      return;
  }
  var auth = new Buffer.from(authHeader.split(' ')[1], 'base64').toString().split(':');
  var user = auth[0];
  var pass = auth[1];
  if (user == 'admin' && pass == 'password') {
      next(); // authorized
  } else {
      var err = new Error('You are not authenticated!');
      res.setHeader('WWW-Authenticate', 'Basic');      
      err.status = 401;
      next(err);
  }
}
app.use(auth);

express-basic-auth 종속성을 설치합니다.

 npm i express-basic-auth

앱을 만들 때 인증 패키지 필요

const app = require('express')();
const basicAuth = require('express-basic-auth');

미들웨어를 다음과 같이 설정합니다.

app.use(basicAuth({
    users: { 'my-username': 'my-password' },
    challenge: true,
}));

모듈이 없어도 기본적인 승인을 구현할 수 있습니다.

//1.
var http = require('http');

//2.
var credentials = {
    userName: "vikas kohli",
    password: "vikas123"
};
var realm = 'Basic Authentication';

//3.
function authenticationStatus(resp) {
    resp.writeHead(401, { 'WWW-Authenticate': 'Basic realm="' + realm + '"' });
    resp.end('Authorization is needed');

};

//4.
var server = http.createServer(function (request, response) {
    var authentication, loginInfo;

    //5.
    if (!request.headers.authorization) {
        authenticationStatus (response);
        return;
    }

    //6.
    authentication = request.headers.authorization.replace(/^Basic/, '');

    //7.
    authentication = (new Buffer(authentication, 'base64')).toString('utf8');

    //8.
    loginInfo = authentication.split(':');

    //9.
    if (loginInfo[0] === credentials.userName && loginInfo[1] === credentials.password) {
        response.end('Great You are Authenticated...');
         // now you call url by commenting the above line and pass the next() function
    }else{

    authenticationStatus (response);

}

});
 server.listen(5050);

출처 : - http://www.dotnetcurry.com/nodejs/1231/basic-authentication-using-nodejs

Express는 이 기능을 제거했으며 이제 기본 인증 라이브러리를 사용할 것을 권장합니다.

사용 방법의 예는 다음과 같습니다.

var http = require('http')
var auth = require('basic-auth')

// Create server
var server = http.createServer(function (req, res) {
  var credentials = auth(req)

  if (!credentials || credentials.name !== 'aladdin' || credentials.pass !== 'opensesame') {
    res.statusCode = 401
    res.setHeader('WWW-Authenticate', 'Basic realm="example"')
    res.end('Access denied')
  } else {
    res.end('Access granted')
  }
})

// Listen
server.listen(3000)

이 경로로 요청을 보내려면 기본 인증용으로 포맷된 Authorization 헤더를 포함해야 합니다.

컬 요청을 먼저 보내려면 base64 인코딩을 받아야 합니다.name:pass 이 면이에에이면rnse에aladdin:opensesame은것것 같은 것YWxhZGRpbjpvcGVuc2VzYW1l

그러면 컬 요청은 다음과 같이 나타납니다.

 curl -H "Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l" http://localhost:3000/

언급URL : https://stackoverflow.com/questions/23616371/basic-http-authentication-with-node-and-express-4

반응형