How do i create and validate Json Web Token in Deno?
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 :)
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 : - //index.ts file code
-
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
-
-
const router = new Router();
-
router
-
.get("/", (context) => {
-
context.response.body = "JWT Demo";
-
})
-
-
const app = new Application();
-
app.use(router.routes());
-
app.use(router.allowedMethods());
-
-
await app.listen({ port: 8000 });
-
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 - // index.ts file code
-
...
-
-
import { makeJwt, setExpiration, Jose, Payload } from "https://deno.land/x/djwt/create.ts";
-
-
const key = "secret-key";
-
const payload: Payload = {
-
iss: "Amit",
-
exp: setExpiration(new Date().getTime() + 60000),
-
};
-
const header: Jose = {
-
alg: "HS256",
-
typ: "JWT",
-
};
-
-
-
const router = new Router();
-
router
-
.get("/", (context) => {
-
context.response.body = "JWT Demo";
-
})
-
.get("/generate", (context) => {
-
context.response.body = makeJwt({ header, payload, key }) + "\n";
-
})
-
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 - // index.ts file code
-
...
-
-
import { validateJwt } from "https://deno.land/x/djwt/validate.ts";
-
-
...
-
-
router
-
.get("/", (context) => {
-
context.response.body = "JWT Demo";
-
})
-
.get("/generate", (context) => {
-
context.response.body = makeJwt({ header, payload, key }) + "\n";
-
})
-
.get("/validate/:token", async (context) => {
-
if ( context.params && context.params.token && (await validateJwt(context.params.token, key)).isValid) {
-
context.response.body = "Correct JWT\n";
-
} else {
-
context.response.body = "Incorrecct JWT\n";
-
}
-
});
-
-
...
-
-
-
-
-
-
-
...
Sign in to post your reply or Sign up for a free account.
Similar topics
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...
...
|
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...
|
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).
...
|
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...
|
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...
|
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 : " "
}
|
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+"}");
}
|
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"
|
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...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
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...
|
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...
|
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)...
|
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...
|
by: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
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....
|
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
| |