By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
462,885 Members | 753 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 462,885 IT Pros & Developers. It's quick & easy.

How do i create and validate Json Web Token in Deno?

P: 5
How do i create and validate Json Web Token in Deno?
4 Days Ago #1
Share this Question
Share on Google+
1 Reply

P: 1
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 :)
4 Days Ago #2

Post your reply

Sign in to post your reply or Sign up for a free account.