一、Bearer認證方式的概念和原理
Bearer認證方式是一種常見的授權驗證方案,其核心在於使用訪問令牌來驗證用戶身份。Bearer是OAuth2.0協議中一個基於令牌的認證機制,即使用令牌而不是密碼來獲取受保護的資源。
與其他類型的令牌相比,Bearer Token最直接的特徵是令牌可以使用不同的數字證書加密,例如基於HTTPS的加密,因此Bearer Token能夠提供更加全面的安全保護。
Bearer Token是OAuth2.0中最主要的一種令牌類型,流程如下:
+------------+ +---------------+ | Resource | | Authorization | | Server | 1. Request to access user | Server | | | account | | | +------------------------------->| | | | | | | | | | | | | | | | | | | | 4. Issue access token | | | <-------------------------------+ | | | | | | | 5. Access Token | | | | | | | | | | | | | | | |2.Deliver response with | | | | authorization server URL | | | | token | | | | | | | | | | | | | | +------------+ +---------------+
Bearer Token通過使用訪問令牌來驗證用戶的身份。這種驗證方式由OAuth2.0所提供。
Bearer Token主要由以下兩部分構成:
令牌:Bearer Token它是一組由伺服器發放的字元串代碼,同時其通常具有特定的過期時間。
授權:Bearer Token通過有效的網路驗證,來確定令牌所有者使用該令牌可以訪問哪些資源。
二、構建一個基於Bearer Token的驗證機制
開發一個基於Bearer Token驗證的機制需要以下步驟:
第一步、開發Server部分代碼
const express = require('express'); const jwt = require('jsonwebtoken'); const { authenticate } = require('./middlewares/authenticate'); const app = express(); const port = process.ENV.PORT || 3000; const user = [ { id: 1, username: 'user1', password: 'password1' }, { id: 2, username: 'user2', password: 'password2' } ]; app.use(express.json()); app.get('/', (req, res) => { res.send('Hello World!'); }); app.post('/login', (req, res) => { const { username, password } = req.body; const userFound = user.find(user => { return user.username === username && user.password === password; }); if (userFound) { const token = jwt.sign(userFound, 'secretkey'); res.json({ token }); } else { res.status(401).json({ message: 'Invalid credentials' }); } }); app.get('/secret', authenticate, (req, res) => { res.json(req.user); }); app.listen(port, () => { console.log(`Server started on port ${port}`); });
第二步、開發authenticate中間件代碼
const jwt = require('jsonwebtoken'); const authenticate = (req, res, next) => { const authHeader = req.headers.authorization; if (authHeader) { const token = authHeader.split(' ')[1]; jwt.verify(token, 'secretkey', (err, user) => { if (err) { return res.status(401).json({ message: 'Invalid or expired token' }); } req.user = user; next(); }); } else { res.status(401).json({ message: 'Token not found' }); } }; module.exports = { authenticate };
第三步、測試API
const request = require('supertest'); const app = require('../index'); const token = jwt.sign({ id: 1 }, 'secretkey'); describe('GET /secret', () => { it('Should return 401 if no token', async () => { const res = await request(app).get('/secret'); expect(res.statusCode).toEqual(401); expect(res.body.message).toEqual('Token not found'); }); it('Should return 401 if invalid token', async () => { const res = await request(app) .get('/secret') .set('Authorization', 'Bearer ' + 'invalidtoken'); expect(res.statusCode).toEqual(401); expect(res.body.message).toEqual('Invalid or expired token'); }); it('Should return 200 if valid token', async () => { const res = await request(app) .get('/secret') .set('Authorization', `Bearer ${token}`); expect(res.statusCode).toEqual(200); }); });
三、Bearer Token在實際場景中的應用
Bearer Token的應用非常廣泛,在許多常見的API驗證方案中都有採用,例如:
1、Google APIs
Google APIs使用OAuth2.0並基於JWT或OAuth2.0的Bearer Token進行訪問令牌驗證。
2、Stripe APIs
Stripe APIs也採用OAuth2.0並基於JWT或OAuth2.0的Bearer Token進行訪問令牌驗證,其藉助於Authorization伺服器以及Token伺服器實現訪問許可權管理。
3、GitHub APIs
GitHub APIs採用OAuth2.0進行驗證,並基於OAuth2.0的Bearer Token進行訪問令牌驗證。
通過以上案例可以看出,Bearer Token的應用非常廣泛,並且在實際中大量被使用。Bearer Token可以幫助開發者構建簡單、快速和安全的驗證方案,同時其也是一種基於OAuth2.0的應用的好選擇。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/287437.html