Learning Diary: JSON WEB TOKEN,学习笔记

in #programming8 years ago (edited)

Screen Shot 2018-04-03 at 12.56.27 AM.png

Hello Steemit friends, so today I stumbled upon JWT, or known as JSON WEB TOKEN, where how it work is that after user have login successfully to your website using username and password, your server should pass them a token, then the user can just use that token to access all the API on your website

大家好,今天学习了JWT,也就是JSON WEB TOKEN, 原理就是用户在login了你的网站之后,你的server就给他们一棵token,用户可以拿着token用你网站上的API而不用一直重复login

the benefit is that you can set expiry time on the token so that after 5 or 10 minutes the user should be logged out and if they want to access the website again, they need to relogin again. Another usefulness is that all the heavy security checking such as number of login attempt, 2FA or SMS can be done on the login API only while the rest of the API just need to check the token, so it ease up the coding alot

好处就是你可以在那棵token放入失效日期,比如5或10分钟,那过了那些时间以后用户要用你的网站他们就需要重新login,就不怕token被偷。有了token后,所有重要的检查比如login次数,2FA,SMS等等只要在一个login API检查就行了,其他API只需要查token就行了,省下大量的代码

So below is the step to setup JWT
以下是如何用token

  1. SSH into your server

  2. Go to the folder where all your API resides in

  3. Install php-jwt using below code,安装
    composer require firebase/php-jwt

  4. On your login script, use below code to generate token
    以下是如何创造一个token给用户

require_once('vendor/autoload.php');  //installation folder might differ
use \Firebase\JWT\JWT;
define('SECRET_KEY’,’YOUR_SECRET_KEY’);
define('ALGORITHM','HS512');
$tokenId    = base64_encode(random_bytes(32));
$issuedAt   = time();
$notBefore  = $issuedAt + 1;  //Adding 1 seconds
$expire     = $notBefore + 10; // Adding 60 seconds
$serverName = 'https://www.example.com'; // set your domain name 
$data = [
                        'iat'  => $issuedAt,         // Issued at: time when the token was generated
                        'jti'  => $tokenId,          // Json Token Id: an unique identifier for the token
                        'iss'  => $serverName,       // Issuer
                        'nbf'  => $notBefore,        // Not before
                        'exp'  => $expire,
                        'data' => [                  // Data related to the logged user you can set your required data
                                    'fname'   => $myfname, // firstame from the users table
                                     'uname' => $myuname   // username from users table
                                  ]
                    ];
$secretKey = base64_decode(SECRET_KEY);
$mytoken = JWT::encode(
                            $data, //Data to be encoded in the JWT
                            $secretKey, // The signing key
                             ALGORITHM
                           );
  1. once the user get the token, user can always pass the token back to the server, and server can verify it using the below code
    以下是如何检查token是否正确

<?php
require_once('vendor/autoload.php');
use \Firebase\JWT\JWT;
define('SECRET_KEY’,’YOUR_SECRET_KEY’);
define('ALGORITHM','HS512');
if(!empty($_GET))
{
$mytoken = $_GET['token'];
try
{
  $secretKey = base64_decode(SECRET_KEY);
  $DecodedDataArray = JWT::decode($mytoken, $secretKey, array(ALGORITHM));
  echo "{'status' : 'success' ,'data':".json_encode($DecodedDataArray)." }";die();
}
catch (Exception $e)
{
  echo "{'status' : 'fail' ,'msg':'Unauthorized'}";die();
}
}
?>

thanks for reading
谢谢阅读

Sort:  

That's nice post! full of information.
It will prove beneficial for those who want to join JWT.
Thanks to inform us.

你好!cn区点赞机器人 @cnbuddy 很开心你能成为cn区的一员。如果我打扰到你,请回复“取消”。

Thank you for sharing your posts with us. This post was curated by TeamMalaysia as part of our community support. Looking forward for more posts from you.

To support the growth of TeamMalaysia Follow our upvotes by using steemauto.com and follow trail of @myach

Vote TeamMalaysia witness bitrocker2020 using this link vote bitrocker2020 witness

Coin Marketplace

STEEM 0.05
TRX 0.33
JST 0.079
BTC 63604.63
ETH 1694.37
USDT 1.00
SBD 0.39