The Internet standard used to construct tokens for an application is JSON Web Token. JSON data is owned by these tokens and is cryptographically signed. JWT is a good way of sending information between parties securely. And it is possible to sign JWTs, because you can be sure that the senders are who they claim they are. And you can also check that the content has not been tampered with, as the signature is created using the header and the payload.
JWT can contain user information in the payload and can be used to authenticate the user in the session as well. First, let's set up a Deno server to accept requests, since we are using the Oak system for it, as you can see below, it is very simple and few lines of codes.
// index.ts
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
const router = new Router();
router
.get("/", (context) => {
context.response.body = "JWT Example!";
})
const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
await app.listen({ port: 8000 });
Let's import djwt functions to generate JWT token once our programme is ready to accept request, we can use a secret key in the below code, expiry time for JWT token in 1 hour from the time programme will run and we are using HS256 algorithm.
You can now get a brand new token on http:/localhost:8000 / generate by adding the below code to index.ts and upgrading the router as shown below.
// index.ts
...
import { makeJwt, setExpiration, Jose, Payload } from "https://deno.land/x/djwt/create.ts";
const key = "secret-key";
const payload: Payload = {
iss: "Jon Doe",
exp: setExpiration(new Date().getTime() + 60000),
};
const header: Jose = {
alg: "HS256",
typ: "JWT",
};
const router = new Router();
router
.get("/", (context) => {
context.response.body = "JWT Example!";
})
.get("/generate", (context) => {
context.response.body = makeJwt({ header, payload, key }) + "\n";
})
I hope this would be helpful to you :)