473,322 Members | 1,510 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

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

7 Nibble
How do i create and validate Json Web Token in Deno?
Oct 16 '20 #1
3 5074
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 :)
Oct 16 '20 #2
Ishan Shah
47 32bit
To generate the JWT token in Deno
First, set up a Deno server to accept requests for it, we will use the Oak framework which is quite simple and a few lines of codes as following :

Expand|Select|Wrap|Line Numbers
  1. //index.ts file code
  2. import { Application, Router } from "https://deno.land/x/oak/mod.ts";
  3.  
  4. const router = new Router();
  5. router
  6.   .get("/", (context) => {
  7.     context.response.body = "JWT Demo";
  8.   })
  9.  
  10. const app = new Application();
  11. app.use(router.routes());
  12. app.use(router.allowedMethods());
  13.  
  14. await app.listen({ port: 8000 });
  15.  
Add the following code in index.ts and update the router as shown below, we can now get a brand new token on http;//localhost:800/generate

Expand|Select|Wrap|Line Numbers
  1. // index.ts file code
  2. ...
  3.  
  4. import { makeJwt, setExpiration, Jose, Payload } from "https://deno.land/x/djwt/create.ts";
  5.  
  6. const key = "secret-key";
  7. const payload: Payload = {
  8.   iss: "Amit",
  9.   exp: setExpiration(new Date().getTime() + 60000),
  10. };
  11. const header: Jose = {
  12.   alg: "HS256",
  13.   typ: "JWT",
  14. };
  15.  
  16.  
  17. const router = new Router();
  18. router
  19.   .get("/", (context) => {
  20.     context.response.body = "JWT Demo";
  21.   })
  22.   .get("/generate", (context) => {
  23.     context.response.body = makeJwt({ header, payload, key }) + "\n";
  24.   })
  25.  
Validating a JWT token

After you get a JWT token you can validate the token by validateJwt function in djwt, let's import the validateJwt and add one more route/validate/:token

Now you can confirm any token by passing it to a route like-http://localhost:800/validate/jwt_token
where jwt_token is a place holder, so it's mandatory to replace it with a real JWT token

Expand|Select|Wrap|Line Numbers
  1. // index.ts file code
  2. ...
  3.  
  4. import { validateJwt } from "https://deno.land/x/djwt/validate.ts";
  5.  
  6. ...
  7.  
  8. router
  9.   .get("/", (context) => {
  10.     context.response.body = "JWT Demo";
  11.   })
  12.   .get("/generate", (context) => {
  13.     context.response.body = makeJwt({ header, payload, key }) + "\n";
  14.   })
  15.   .get("/validate/:token", async (context) => {
  16.     if ( context.params && context.params.token && (await validateJwt(context.params.token, key)).isValid) {
  17.       context.response.body = "Correct JWT\n";
  18.     } else {
  19.       context.response.body = "Incorrecct JWT\n";
  20.     }
  21.   });
  22.  
  23. ...
  24.  
  25.  
  26.  
  27.  
  28.  
  29.  
  30. ...
Jan 1 '21 #3
scode
1 Bit
you can check this youtube tutorial because it is explained here:

https://www.youtube.com/watch?v=9W_BUMeMQI8
May 6 '21 #4

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

Similar topics

20
by: Luke Matuszewski | last post by:
Welcome As suggested i looked into JSON project and was amazed but... What about cyclical data structures - anybody was faced it in some project ? Is there any satisactional recomendation... ...
8
by: MD | last post by:
I want to put the xml document into the JSON like the following. However, usually my xml document has new line for the xml document. Is there any option to skip the new line in the JSON or I...
5
by: Tom Cole | last post by:
Let's say I have the following JSON string returned from a server-side process: { values: } I then create a JSON object from it using eval() (tell me if this is not what should be done). ...
2
by: IamIan | last post by:
Hello all, I am confused as to why including 08 or 09 in a sequence (list or tuple) causes this error. All other numbers with a leading zero work. is fine is fine produces...
1
by: Newbie19 | last post by:
I am trying to get an API to connect to a Server that controls a database, but I need to generate a Security Token (Guid). I was told to make it in the Web.config files located on the server, how...
4
by: pistacchio | last post by:
hi to all! i have the following code (i stripped down the code to a short example, but still it does reproduce the problem): var objs = new Array(); obj = { parameter : " " }
1
by: SirCodesALot | last post by:
Hi All, Is it possible to create an JSON object from a string? For example var myArray = new Array(10) for (var i=0;i<10;i++) { myArray.push("{idx:"+i+",val:"+i+"}"); }
3
Claus Mygind
by: Claus Mygind | last post by:
what am I doing wrong in creating the json object here I have a javaScript array the data looks like this 0 feature "Point 1" pinColor "red" 1 feature "Point 2" pinColor "blue"
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.