3.4.2.Securing API with Basic Authentication

  • Basic authentication

    • Use the HTTP header authorization

    • 將User: Password用Base64加密後放到HTTP header的Authorization

  • Basic authentication weakness

    • 1.若使用HTTP則header會被截取

    • 2.若使用Session儲存credential則與REST相違背

    • 3.容易被竊取

  • Requirements

  • 程式碼解析

// Basic Authentication
// Part of the course on "REST API Design Development & Management"
// http://www.acloudfan.com

var     express = require('express')
var     basicauth = require(__dirname + '/basicauth')


// Express app setup
var app = express();
var router = express.Router();

// This is the passport middlewae function that get called first
var  auth = basicauth.auth
// Setup the route with basic authentication
router.get('/private',auth,function(req, res){
    res.send('Access granted to private resource!!!')
});

app.use(router);

app.listen(3000);

console.log('Listening on 3000')


// This has all the code for implementing basic auth
var passport = require('passport')
// This the strategy for basic authentication
var BasicStrategy = require('passport-http').BasicStrategy

// Access to the users data
var users = require(__dirname + '/userdata/users')

// Setup the passport strategy
passport.use(new BasicStrategy(function (username, password, done) {

    var user = users.checkCredentials(username,password)
    if(user)
        return done(null, true)
    else
        return done(null, false)
}));

// This is the middleware function that gets invoked
var auth = passport.authenticate('basic', { session: false })

exports.auth = auth;

// Hardcoded users for testing
// Can be changed to store the users in a database
var users = [
    { id: 1, name: "jim", email: "jim@mail.com", password: "jim123" },
    { id: 2, name: "sam", email: "sam@mail.com", password: "sam123" }
];


var checkCredentials = function (username, password) {
    // Check if username/password are good
    var user = users.find(function (u) {
        return u.name === username && u.password === password;
    });

    return user
}

exports.checkCredentials = checkCredentials;
  • 用Postman測試

    • Authorization

      • Type: Basic Auth

      • Username/ Password

Last updated

Was this helpful?