在現(xiàn)代Web應(yīng)用中,API認(rèn)證是確保應(yīng)用安全的關(guān)鍵步驟。通過(guò)JSON Web Tokens(JWT),我們可以有效地保護(hù)API路由,確保只有經(jīng)過(guò)認(rèn)證的用戶(hù)才能訪問(wèn)特定資源。

技術(shù)棧介紹

為了實(shí)現(xiàn)這一目標(biāo),我們將使用以下技術(shù)棧:

項(xiàng)目初始化

首先,創(chuàng)建一個(gè)項(xiàng)目文件夾并初始化npm項(xiàng)目。在終端中運(yùn)行以下命令:

mkdir node-auth-api
cd node-auth-api
npm init -y

搭建基本API

安裝必要的依賴(lài):

npm install express jsonwebtoken
npm install -g nodemon

創(chuàng)建app.js文件,并編寫(xiě)基本的Express API代碼:

const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();

app.get('/api', (req, res) => {
  res.json({ message: 'Welcome to the API' });
});

const PORT = 5000;
app.listen(PORT, () => {
  console.log(Server started on port ${PORT});
});

運(yùn)行以下命令啟動(dòng)服務(wù)器:

nodemon app.js

使用Postman測(cè)試API:

GET http://localhost:5000/api

創(chuàng)建受保護(hù)路由

接下來(lái),創(chuàng)建一個(gè)受保護(hù)的POST路由:

app.post('/api/posts', (req, res) => {
  res.json({ message: 'Post created' });
});

測(cè)試此路由:

POST http://localhost:5000/api/posts

實(shí)現(xiàn)登錄路由

創(chuàng)建一個(gè)登錄路由,用于生成和返回JWT:

app.post('/api/login', (req, res) => {
  // 在實(shí)際應(yīng)用中,這里應(yīng)該驗(yàn)證用戶(hù)憑據(jù)
  const user = {
    id: 1,
    username: 'Brad',
    email: 'brad@gmail.com'
  };

  jwt.sign({ user }, 'your_jwt_secret', { expiresIn: '30s' }, (err, token) => {
    if (err) throw err;
    res.json({ token });
  });
});

測(cè)試登錄路由:

POST http://localhost:5000/api/login

驗(yàn)證令牌

實(shí)現(xiàn)一個(gè)中間件函數(shù),用于驗(yàn)證請(qǐng)求中的JWT:

function verifyToken(req, res, next) {
  const bearerHeader = req.headers['authorization'];
  if (typeof bearerHeader !== 'undefined') {
    const bearer = bearerHeader.split(' ');
    const bearerToken = bearer[1];
    req.token = bearerToken;
    jwt.verify(req.token, 'your_jwt_secret', (err, authData) => {
      if (err) {
        res.sendStatus(403);
      } else {
        next();
      }
    });
  } else {
    res.sendStatus(403);
  }
}

將中間件應(yīng)用于受保護(hù)路由:

app.post('/api/posts', verifyToken, (req, res) => {
  res.json({ message: 'Post created', authData: req.authData });
});

測(cè)試受保護(hù)路由

在Postman中測(cè)試受保護(hù)路由。在請(qǐng)求頭中包含JWT:

Authorization: Bearer <your_jwt_token>
POST http://localhost:5000/api/posts

設(shè)置令牌過(guò)期時(shí)間

在登錄路由中設(shè)置JWT過(guò)期時(shí)間:

jwt.sign({ user }, 'your_jwt_secret', { expiresIn: '30s' }, (err, token) => {
  if (err) throw err;
  res.json({ token });
});

測(cè)試過(guò)期的JWT:

POST http://localhost:5000/api/posts

總結(jié)

通過(guò)本教程,我們學(xué)習(xí)了如何使用JWT保護(hù)API路由。從項(xiàng)目搭建到令牌驗(yàn)證,我們?nèi)嬲莆樟薃PI認(rèn)證的核心技能。希望這些內(nèi)容對(duì)你有所幫助!

原文引自YouTube視頻:https://www.youtube.com/watch?v=7nafaH9SddU

上一篇:

REST API 的基礎(chǔ)知識(shí)

下一篇:

API的未來(lái):從基礎(chǔ)到進(jìn)階,如何高效管理與集成各類(lèi)API
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門(mén)場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)