3. Manage your authentication token

We want to manage our own cookie for authenticating the user into our app. We will user another npm library for this.

npm install jsonwebtoken

We create a new file "authenticate/token.js" in which we will manage our own authentication token.

const jsonwebtoken = require("jsonwebtoken");

module.exports = {
    getCookieName,
    getCookieOptions,
    createToken
};

    // name our cookie
    function getCookieName() {
        return "my_jwt_token";
    }

    // same site cookie info...
    function getCookieOptions() {
        var objOptions= {
            sameSite: "Lax"
        };
        if(!gConfig.isDebug){
            objOptions.secure=true;
        }
        return objOptions
    }

    // JWT signed payload 
    function createToken(req) {
        let payload = {
            username: (req!=null && req.user!=null && req.user.username!=null) ? req.user.username.toString() : null,
            connector: (req!=null && req.user!=null && req.user.connector!=null) ? req.user.connector : null,
            blockchain: (req!=null && req.user!=null && req.user.blockchain!=null) ? req.user.blockchain : null,
            authorizations: (req!=null && req.user!=null && req.user.authorizations!=null) ? req.user.authorizations : null,
            provider_wallet: (req!=null && req.user!=null && req.user.provider_wallet!=null) ? req.user.provider_wallet : null,
            wallet_address: (req!=null && req.user!=null && req.user.wallet_address!=null) ? req.user.wallet_address : null
        };
        return jsonwebtoken.sign(payload, "mySecret", {
            expiresIn: "72h"
        });
    }

Last updated