Skip to main content

快速开始/后端API/Node.JS API/

Node.JS API

授权

验证访问令牌

安装依赖

npm install --save express-oauth2-jwt-bearer

配置中间件

server.js

const express = require('express');
const app = express();
const { auth } = require('express-oauth2-jwt-bearer');

// Authorization middleware. When used, the Access Token must
// exist and be verified against the AuthOK JSON Web Key Set.
const checkJwt = auth({
audience: 'undefined',
issuerBaseURL: `https://YOUR_DOMAIN/`,
});

保护 API 端点

server.js
const { requiredScopes } = require('express-oauth2-jwt-bearer');
const checkScopes = requiredScopes('read:messages');

// 不需要认证
app.get('/api/public', function(req, res) {
res.json({
message: 'Hello from a public endpoint! You don\'t need to be authenticated to see this.'
});
});

// 需要认证
app.get('/api/private', checkJwt, function(req, res) {
res.json({
message: 'Hello from a private endpoint! You need to be authenticated to see this.'
});
});

// 需要 scope 验证
app.get('/api/private-scoped', checkJwt, checkScopes, function(req, res) {
res.json({
message: 'Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this.'
});
});

使用 API

在应用中调用API

curl --request GET \
--url http://localhost:3010/api/private \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN'

获取访问令牌

在单页应用 或 移动端/原生应用中, 在授权成功后,你需要获取 访问令牌. 如何获取令牌以及如何调用API将取决于您正在开发的应用程序类型和使用的框架.

更多信息请参考相关应用程序快速入门:

curl --request POST \
--url 'https://YOUR_DOMAIN/oauth/token' \
--header 'content-type: application/x-www-form-urlencoded' \
--data grant_type=client_credentials \
--data 'client_id=YOUR_CLIENT_ID' \
--data client_secret=YOUR_CLIENT_SECRET \
--data audience=YOUR_API_IDENTIFIER

测试API

1. 调用被保护端点

curl --request GET \
--url http://localhost:3010/api/private

以上调用会返回 401 HTTP (Unauthorized) 状态码.

携带 AccessToken 进行调用

curl --request GET \
--url http://localhost:3010/api/private \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN'

此时,会返回成功响应.

2. 调用被作用域保护的端点

curl --request GET \
--url http://localhost:3010/api/private-scoped \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN'