Zaubrik / djwt

Create and verify JSON Web Tokens (JWT) with Deno or the browser.
MIT License
228 stars 23 forks source link

The jwt's signature does not match the verification signature. #74

Closed youwei997 closed 2 years ago

youwei997 commented 2 years ago

请问,编辑器reload后(没有修改代码),重新调用接口,之前生成的token失效是什么原因 Please ask, after the editor reloads (without modifying the code), the interface is called again, and what is the reason for the failure of the previously generated token

import { Application, Router } from "https://deno.land/x/oak/mod.ts";
import { create, verify } from "https://deno.land/x/djwt@v2.7/mod.ts";
import { oakCors } from "https://deno.land/x/cors/mod.ts";

const app = new Application();
const router = new Router();

const jwtKey = await crypto.subtle.generateKey(
    { name: "HMAC", hash: "SHA-512" },
    true,
    ["sign", "verify"]
);

const database = { username: "deno-jwt", password: "learn" };

router.post("/login", async (ctx) => {
    const result = ctx.request.body();
    const value = await result.value;
    const { username, password } = value;
    if (username === database.username && password === database.password) {
        const jwt = await create(
            { alg: "HS512", typ: "JWT" },
            { username },
            jwtKey
        );
        ctx.response.body = {
            token: "Bearer " + jwt,
        };
    }
});
router.get("/home", async (ctx) => {
    const headers = ctx.request.headers;
    const token = (headers.get("authorization") as any).split(" ")[1];
    const tokenInfo = await verify(token, jwtKey);
    ctx.response.body = tokenInfo;
});
app.use(oakCors()); // Enable CORS for All Routes
app.use(router.routes(), router.allowedMethods());

await app.listen({ port: 8000 });
jpsSO commented 2 years ago

Every time the code runs, it creates a new jwtKey. Tokens that have been created with a different key before can't be verified with the new key. Instead of creating a new key every time, just create it once, store it in a config file and load it from there.

youwei997 commented 2 years ago

Please ask how to restrict it to create it only once. I'm going to use a variable to load the key I created and determine if it exists, but every time I edit it, the variable state is cleared, and i need to use a storage tool. Thank you

jpsSO commented 2 years ago

An issue on GitHub should be used to report real bugs or issues in the library. It turns out that the issue you reported above is not an issue in djwt but in your own code. Therefore this issue should be closed now. The questions about how you could solve your programming questions should be asked in a programming forum.

youwei997 commented 2 years ago

应该使用 GitHub 上的问题来报告库中的真正错误或问题。事实证明,您上面报告的问题不是 djwt 中的问题,而是您自己的代码中的问题。因此,这个问题现在应该关闭。应该在编程论坛中询问有关如何解决编程问题的问题。 OK, thanks