Translate

In javascript we will calculate the remaining time for token expiration


Simple when we create a token using JWT.
We use a syntax of type:
const tokenExpirationSeconds = 60; //one minute.
See the demo also working on jsfiddle

In javascript we will calculate the remaining time for token expiration.

Simple when we create a token using JWT.
when we store a value, it is stored in seconds determining the expiration time, and we use that expiration time to generate a timestamp, which is linked to the key payload, for example in node.js

const crypto = require('crypto');
const tokenExpirationSeconds = 120;
class TokenManager {
  static createJwt(issuer, privateKey) {
    if (!issuer || !privateKey) {
      return false;
    }
    const header = {
      alg: 'RS256',
      typ: 'JWT'    };
    const payload = {
      iss: issuer,
      exp: parseInt(new Date().getTime() / 1000, 10) + tokenExpirationSeconds
    };
    const pkg = Buffer.from(JSON.stringify(header)).toString('base64') + "." + Buffer.from(JSON.stringify(payload)).toString('base64');
    const sign = crypto.createSign('RSA-SHA256');
    sign.update(pkg);
    const signature = sign.sign(privateKey, 'base64');

    return pkg + "." + signature;
  }
}

then exactly after key creation, using a method similar to the method mentioned above. We use the tokenExpirationSeconds = 120, and the payload exp which is the timestamp. Then we calculate:

var re = 0;
var expired = tokenExpirationSeconds;
var dayDataBase = timestampSaved;
var dayLocal = parseInt(new Date().getTime() / 1000, 10) + expired;
re = dayLocal - dayDataBase;
    if(re<expired){
     console.log("Token is still valid"); 
    }else{
     console.log("Token expired, generate a new token"); 
    } 

style.css

input[type=text], select {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid red;
  border-radius: 4px;
  box-sizing: border-box;
}
.csave{
  width: 100%;
  background-color: #4CAF50;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.csave:hover {
  background-color: #45a049;
}
.creset{
  width: 100%;
  background-color: #4CAF50;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.creset:hover {
  background-color: #45a049;
}
#diving {
  border-radius: 5px;
  background-color: #333;
  padding: 20px;
}

index.html

<h2>In javascript we will calculate the remaining time for token expiration.</h2>
<h3>
    Simple when we create a token using <a href="https://jwt.io/introduction/" target="_blank">JWT</a>.<br />
    We use a syntax of type: <br />const tokenExpirationSeconds = 60; //one minute.<br />
    var timeStampToExpire = parseInt(new Date (). getTime () / 1000, 10) tokenExpirationSeconds //<br />
    This will generate a timeStamp .
    We saved this timeStamp, and then calculated the remaining time for token expiration.
    Look</h3>

<div id="diving ">
    <label id="info" for="time">time in milliseconds</label>
    <input type="text" id="time" name="milliseconds" maxlength="3" required="true" placeholder="time in seconds" />

    <button class="csave" id="save">store time</button>
    <button class="creset" id="reset" value="reset stored cookie">reset stored cookie</button>
</div>

javascript.js

var re = 0;
var timeStamp = 0;
var timeStampExpirator = getCookie("timeStampToken");
var timeInSeconds = getCookie("timeInSeconds");
var preencha_este_campo = "Fill in this field with the value to be saved.";
var tokenChecker;
var cleancookie = document.getElementById("reset");
var mSubmit = document.getElementById("save");
var mTime = document.getElementById("time");
var mInfo = document.getElementById("info");
   console.log("cookie_length:"+timeStampExpirator.length);
   
 if(timeStampExpirator.length ==0){
  cleancookie.style.display = "none";
  mInfo.innerHTML = "No timestamp saved";   
  console.log("set token time in seconds") 
    
   mSubmit.addEventListener('click',(a)=>{
      if(mTime.value.length>0){
       var a = parseInt(mTime.value);
       var timeStamp = parseInt(new Date().getTime() / 1000, 10 ) + a;
      document.cookie = "timeStampToken="+timeStamp;
      document.cookie = "timeInSeconds="+mTime.value; 
      console.log("StampToken was saved at a cookie! reload the page "+timeStamp) 
      console.log("timeToken was saved at a cookie! reload the page "+mTime.value) 
    mInfo.innerHTML = "StampToken was saved at a cookie! reload the page"; 
                 mSubmit.innerHTML = "Reload"; 
                 mSubmit.setAttribute("onclick","window.location.reload()");
  
    
      }else{
        mInfo.innerHTML = preencha_este_campo; 
       console.log(preencha_este_campo) 
      }  
   });
  
 }else{
  tokenExpirationChecker();
  mInfo.innerHTML = "Token expiration being checked";
  cleancookie.style.display = "block";
  mSubmit.style.display = "none";
   var dayDataBase = timeStampExpirator;
    var a = parseInt(timeInSeconds);
   var dayLocal = parseInt(new Date().getTime() / 1000, 10) + a;
   re = dayLocal - dayDataBase;
   console.log("Token expiration being checked:"+re+" / "+a);  
    mInfo.innerHTML = "Token expiration being checked:"+re+" / "+a;  
 }
  
 
        
    cleancookie.addEventListener('click',(a)=>{
     cleancookie.style.display = "none";
   document.cookie = "timeStampToken=";
   document.cookie = "timeInSeconds=";
   console.log("reset stored cookie: SUCCESS")
   mInfo.innerHTML = "reset stored cookie: SUCCESS"; 
   mSubmit.innerHTML = "store time again"; 
   mSubmit.style.display = "block";
   mSubmit.addEventListener('click',(a)=>{
      if(mTime.value.length>0){
       var a = parseInt(mTime.value);
       var timeStamp = parseInt(new Date().getTime() / 1000, 10 ) + a;
      document.cookie = "timeStampToken="+timeStamp;
      document.cookie = "timeInSeconds="+mTime.value; 
      console.log("StampToken was saved at a cookie! reload the page "+timeStamp) 
      console.log("timeToken was saved at a cookie! reload the page "+mTime.value) 
    mInfo.innerHTML = "StampToken was saved at a cookie! reload the page"; 
                 mSubmit.innerHTML = "Reload"; 
                 mSubmit.setAttribute("onclick","window.location.reload()");
  
    
      }else{
        mInfo.innerHTML = preencha_este_campo; 
       console.log(preencha_este_campo) 
      }  
   });
   clearTimeout(tokenChecker);
      });

   
    function tokenExpirationChecker(){
    tokenChecker = setTimeout(function(){    
     var dayDataBase = timeStampExpirator;
     var a = parseInt(timeInSeconds);
     var dayLocal = parseInt(new Date().getTime() / 1000, 10) + a;
     re = dayLocal - dayDataBase;
     console.log("Token expiration being checked:"+re+" / "+a);  
                 mInfo.innerHTML = "Token expiration being checked:"+re+" / "+a;     
       if(re>=timeInSeconds){
        console.log("Token has expired        :"+re+" / "+a);
        mInfo.innerHTML = "TOKEN HAS EXPIRED"; 
        cleancookie.style.display = "none";
        mSubmit.style.display = "block";
         document.cookie = "timeStampToken=";
                        document.cookie = "timeInSeconds=";
          mSubmit.addEventListener('click',(a)=>{
            if(mTime.value.length>0){
             var a = parseInt(mTime.value);
             var timeStamp = parseInt(new Date().getTime() / 1000, 10 ) + a;
            document.cookie = "timeStampToken="+timeStamp;
            document.cookie = "timeInSeconds="+mTime.value; 
            console.log("StampToken was saved at a cookie! reload the page "+timeStamp) 
            console.log("timeToken was saved at a cookie! reload the page "+mTime.value) 
          mInfo.innerHTML = "StampToken was saved at a cookie! reload the page"; 
           mSubmit.innerHTML = "Reload"; 
           mSubmit.setAttribute("onclick","window.location.reload()");
        
          
            }else{
           mInfo.innerHTML = preencha_este_campo; 
             console.log(preencha_este_campo) 
            }  
          });
        clearTimeout(tokenChecker);
       }else{
       tokenExpirationChecker()   
       }
          
    }
    , 1000);
    }
  

 function getCookie(cname) { 
  var name = cname + "=";
  var ca = document.cookie.split(';');
   for(var i = 0; i < ca.length; i++) {
   var c = ca[i];
    while (c.charAt(0) == ' ') {
    c = c.substring(1);
    }
     if (c.indexOf(name) == 0) {
     return c.substring(name.length, c.length);
   }
  }
  return "";
 }

Postagens mais visitadas deste blog

Parceiros

Instalar Tool for Zello


Powered with


Parceiros



Tranparência


Contatos



© 2017 - 2019 Allanksr [ TFZ ]
Todos os direitos reservados