tsoa-oauth-express
此库可以轻松实现OAuth2身份验证 tsoa 在 表达. 要使用此库,首先将其添加为 npm 依赖于现有的 tsoa 应用程序。
npm i @digicatapult/tsoa-oauth-express
您的身份验证文件(请参阅tsoa关于身份验证设置的文档) 在这里)将需要包含如下内容:
import type express from 'express'
import type * as jwt from 'jsonwebtoken'
import mkExpressAuthentication, { AuthOptions } from '@digicatapult/tsoa-oauth-express'
// module options
const options: AuthOptions = {
...
}
export const expressAuthentication = mkExpressAuthentication(options)
的地方 options Value是具有以下类型和属性的对象:
interface AuthOptions {
securityName?: string
verifyOptions?: jwt.VerifyOptions & { complete?: false }
jwksUri: () => Promise<string>
getAccessToken: (req: express.Request) => Promise<string | undefined>
getScopesFromToken: (decoded: string | jwt.JwtPayload) => Promise<string[]>
tryRefreshTokens: (req: express.Request) => Promise<boolean>
}
| 财产 | 要求 | 描述 |
|---|---|---|
| jwksUri | true | 解析为 uri 对于您的身份提供者 jwks 配置 |
| getAccessToken | true | 类解析JWT Request. 例如,这可能来自an authorization 页眉或 cookie 基于需求 |
| getScopesFromToken | true | 解析为所提供令牌支持的OAuth范围数组 |
| securityName | false | OpenAPI 要保护的安全方案名称 |
| verifyOptions | false | jsonwebtoken 验证选项。看到 jsonwebtoken文档 有关详细信息, |
| tryRefreshTokens | false | 执行令牌刷新。解析为 true 否则刷新成功 false. 默认情况下,它总是解析为 false |
例子
包存储库中包含一个使用OAuth客户机-凭据流对机器对机器(m2m) API进行身份验证的示例实现。它由两个部分组成,一个是预配置的 Keycloak 可以被实例化的实例 docker compose 作为我们的身份提供者和下面的示例应用程序 /。 它实现了 tsoa 服务器。欲了解更多信息,请参阅 Tsoa认证文档 我们的身份验证处理程序示例在 / / authentication.ts示例.
首先打开 Keycloak 实例,从存储库根目录执行:
docker compose up -d
这将自动预配置一个名为 example 客户端保密 example. 然后我们可以通过执行以下命令来获取一个m2m令牌:
curl --request POST \
--url 'http://localhost:3080/realms/example/protocol/openid-connect/token' \
--header 'content-type: application/x-www-form-urlencoded' \
--data grant_type=client_credentials \
--data client_id=example \
--data client_secret=example
属性中返回一个JSON对象,该对象带有JWT验证令牌 access_token 属性的形式为 eyJhbGci...r8TIOfRQ.
然后可以使用以下命令运行示例服务器:
npm run example
该服务器监听端口3000并公开两条路由 /authenticated 和 /unauthenticated 其中只有第一条路由需要认证令牌。例如,我们可以调用
curl http://localhost:3000/unauthenticated
哪个应该返回类似的东西
{ "message": "This route is unauthenticated", "authenticated": false }
但是调用经过验证的路由(curl http://localhost:3000/authenticated)将返回一个错误
{ "message": "unauthenticated" }
提供JWT认证令牌作为认证头的一部分:
curl http://localhost:3000/authenticated --header 'authorization: bearer eyJhbGci...r8TIOfRQ'
导致调用成功:
{ "message": "This route is authenticated", "authenticated": true }