> For the complete documentation index, see [llms.txt](https://jen-hsuan-hsieh.gitbook.io/asp-net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jen-hsuan-hsieh.gitbook.io/asp-net/chapter3rest-api-design-development-and-management/34rest-api-security/342securing-api-with-basic-authentication.md).

# 3.4.2.Securing API with Basic Authentication

* Basic authentication
  * Use the HTTP header authorization
  * 將User: Password用Base64加密後放到HTTP header的Authorization

    ![](https://163116165-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4M0G7tIs4o9F9vSrao%2F-M4M0IVB0ax0vs2ocz_r%2F-M4M0XlcXrrENvoY8osM%2F%E6%9C%AA%E5%91%BD%E5%90%8D23329.jpg?generation=1586302966711503\&alt=media)
* Basic authentication weakness
  * 1.若使用HTTP則header會被截取
  * 2.若使用Session儲存credential則與REST相違背
  * 3.容易被竊取

    ![](https://163116165-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4M0G7tIs4o9F9vSrao%2F-M4M0IVB0ax0vs2ocz_r%2F-M4M0Xlewgno_9EkKGB_%2F%E6%9C%AA%E5%91%BD%E5%90%8D23229.jpg?generation=1586302966711001\&alt=media)
* Requirements
  * [Visual studio code](https://code.visualstudio.com/docs/?dv=win)
  * [node.js](https://nodejs.org/en/)
  * [source code from github](https://github.com/acloudfan/REST-API-CACHING)
    * 1.clone repository

      ```
      git clone https://github.com/acloudfan/REST-API-security.git
      npm install
      ```
* 程式碼解析

```
// 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
