JWT Token Introduction

in #web6 years ago

If you are a mobile developer or a front end developer, you often need to deal with Authentication for user sign in. Traditional way of doing it is using framework and some other way.

JWT

What is JWT?
JWT also known as JSON Web Tokens. JWT is an industry standard method of doing authentication. The best thing about JWT is that it can transfer between different domain.

It mades up with 3 pieces of data: header, payload and key. Where the format looks something like this:

<header>.<payload>.<key>

Code

Quickstart with Node.js

in node REPL:

let's create a function to generate the buffer that we will it later.

function buff(input) {
  return new Buffer(JSON.stringify(input)).toString('base64');
}

Header

Header has 2 claims: type typ and algorithm alg.

let header = {typ: 'JWT', alg: 'HS256'};
let header_jwt = buff(header);

Payload

Payload also contains claims: issuer iss, exp expiration, issue at claim iat, and ...

In this case, you can change iss and username.

let payload = {iat: Date.now(), iss: 'johnson', username: 'johnson'};
let payload_jwt = buff(payload);

Key / Signature

Using node, there is a crypto library. We create a signature with sha256 hash algorithm.

let combiner = header_jwt + '.' + payload_jwt;
let signature = crypto.createHmac('sha256', 'secretkey');
signature.update(combiner);
let key = signature.digest('base64');

Combine everything

let token = header_jwt + '.' + payload_jwt + '.' + key;
console.log(token);

Debug JWT Token

Go to JWT.io Debugger and paster the token that generated just now.
Screen Shot 2017-12-20 at 5.15.46 PM.png

You can check what you done just now! So simply replace the secretkey with your own to check validity of the token.

About Me

I am Lai Weng Han (Johnson), you can find me on Twitter.

Sort:  

The @OriginalWorks bot has determined this post by @superoo7 to be original material and upvoted it!

ezgif.com-resize.gif

To call @OriginalWorks, simply reply to any post with @originalworks or !originalworks in your message!

Coin Marketplace

STEEM 0.33
TRX 0.11
JST 0.034
BTC 66363.68
ETH 3207.73
USDT 1.00
SBD 4.27