Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Authentication using JSON Web Token (jwt) in node.js

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 751
    Comment on it

    Authentication is one of the big part of any application. JSON web token is one of the safest medium of transferring information between two parties. The token is a long encryped string that has 3 parts-

     

    The headers  - It contains the header information

    The paylod - It contains the actual information such the user json object and

    The signature - It is a cryptographic signature

     


    Usage:

    jwt.sign(payload, secretOrPrivateKey, options, [callback])

    payload:

    {
        _id: "adnasdaasdjasdh",
        name: "dinesh rawat",
        email: "dinesh.rawat@evontech.com"
    }

    secretOrPrivateKey:

    It could be anything that is used to make a hash
    ex:-

    "mysupersecretkey"

    options:

    algorithm (default: HS256)

    expiresIn: expressed in seconds or a string describing a time span

    notBefore: expressed in seconds or a string describing a time span

    audience

    issuer

    jwtid

    subject

    noTimestamp

    header


    Example

    // sign with default (HMAC SHA256)
    var jwt = require('jsonwebtoken'); //Sign with HMAC SHA256
    var token = jwt.sign({
                    _id: "adnasdaasdjasdh",
                    name: "dinesh rawat",
                    email: "dinesh.rawat@evontech.com"
                }, "mysupersecretkey", { expiresIn : 60*60*24 });
    
    console.log(token);
    
    /*
    RESULT:
    -------
    
    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1Nzg3NTZlNTI3YjFjMGMzMzgyZWQ4ZWUiLCJlbWFpbCI6Imhhcm5lZXQiLCJ0b2tlbiI6IiIsImlhdCI6MTQ2ODU3NDQ3NiwiZXhwIjoxNDY4NjYwODc2fQ.tcvbLZIkLHWsKObtbDcpjHdGJoGnVtHinj8JAkRigpM
    
    


    Decoding:
     

    var decoded = jwt.decode(token);
    
    // get the decoded payload and header
    var decoded = jwt.decode(token, {complete: true});
    console.log(decoded.header);
    console.log(decoded.payload)

     

    Checkout code from git:

    https://github.com/dinesh-rawat/jwt-authentication.in.nodejs

     

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: