使用 Deno 进行 JWT 身份验证

Lau*_*utt 6 jwt typescript deno

如何在 Deno 中创建和验证 JSON Web Token?

我是 Deno 运行时的新手,所以有一个示例来开始在 Deno 中使用 JWT 会很有帮助。

jps*_*jps 8

这是一个简短的演示,展示了如何使用HS256签名创建 JWT以及如何验证它并提取有效负载。

jwtdemo.ts(基于djwt 1.9 版):

import { verify, create, Header, Payload, getNumericDate } from "https://deno.land/x/djwt@v1.9/mod.ts"

var key = "secret-key";

const algorithm = "HS256"

const header: Header = {
  alg: algorithm,
  typ: "JWT",
  "custom-key":"custom-value"
};

const payload: Payload = {
  iss: "deno-demo",
  exp: getNumericDate(300)  // 300 seconds = 5 minutes from now on
  //exp: getNumericDate(new Date("2020-11-02T19:00:00.000Z"))   // or set a certain date and time
};


const jwt = await create(header, payload, key)
console.log(jwt);

//key = "wrong-key" // this will let the verification fail

try {
    const payload = await verify(jwt,  key, algorithm)
    console.log(payload)
}
catch(ex) {

    console.log(ex.message)
}

Run Code Online (Sandbox Code Playgroud)

helper 方法会getNumericDate(exp)自动设置正确的 unix 时间戳,并将作为参数给出的秒数添加到当前时间或直接使用给定的日期参数。

你可以直接运行上面的demo,所有导入的模块都会自动下载:

deno run jwtdemo.ts
Run Code Online (Sandbox Code Playgroud)

结果是:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImN1c3RvbS1rZXkiOiJjdXN0b20tdmFsdWUifQ.eyJpc3MiOiJkZW5vLWRlbW8iLCJleHAiOjE2MDQzNDI2NDR9.6dbloI7z6M40JSw5JPE_F19SWYaY4sALQ48mxUir8DM
{ iss: "deno-demo", exp: 1604342644 }
Run Code Online (Sandbox Code Playgroud)

或者,如果签名错误:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImN1c3RvbS1rZXkiOiJjdXN0b20tdmFsdWUifQ.eyJpc3MiOiJkZW5vLWRlbW8iLCJleHAiOjE2MDQzNDI2MzN9.XUUSZRsZp0sFdu8RBmzFcOZMXc9ZguA8tPy8n0hI7l4
The jwt's signature does not match the verification signature.
Run Code Online (Sandbox Code Playgroud)

在 node.js 中创建 JWT 的一个显着区别是,我们有预定义的接口HeaderPayload而不是简单的 JSON 和值被检查。

当我设置

const algorithm = "XS256"   // instead of "HS256"
Run Code Online (Sandbox Code Playgroud)

算法检查将失败,程序无法启动:

Check file:///C:/Users/jps/source/deno/jwtdemoV19.ts
error: TS2322 [ERROR]: Type '"XS256"' is not assignable to type 'Algorithm'.
  alg: algorithm,
  ~~~
    at file:///C:/Users/jps/source/deno/jwtdemoV19.ts:8:3

    The expected type comes from property 'alg' which is declared here on type 'Header'
      alg: Algorithm;
      ~~~
        at https://deno.land/x/djwt@v1.9/mod.ts:36:3

TS2345 [ERROR]: Argument of type '"XS256"' is not assignable to parameter of type 'AlgorithmInput'.
        const payload = await verify(jwt,  key, algorithm)
                                                ~~~~~~~~~
    at file:///C:/Users/jps/source/deno/jwtdemoV19.ts:26:42

Found 2 errors.
Run Code Online (Sandbox Code Playgroud)

示例代码使用djwt 1.9 版,目前支持HS256HS512RS256签名算法。未来将添加更多算法,具体取决于 deno 加密模块中支持的可用性。

阅读此答案I 以了解如何验证 RS256 签名令牌。

注意:此答案已被重写以涵盖 1.9 版中 djwt api 的重大更改。这篇文章旧版本基于djwt v1.7