Home > Blockchain >  How to keep idToken in server side?
How to keep idToken in server side?

Time:07-16

Yesterday I figured out how to give a user custom claims. So now upon logging in I fetch the '/getMyClaims' post, and it gets what type of claims they have.

And when I log in as admin, I am able to go to the routes that are only admin, but sometimes randomly, the block is reverting back to false so it disallows even the admin. How do I keep the idToken recognized everytime? I have been having a hard time trying to find out how to make this work even when the documents provided and most resources are either for react or vue. I am using nodejs, and plain javascript and html.

My thoughts were to store the block, but I guess it is refreshing and then the variable block reverts to undefined.

Here is my server.js:

    var block;

var blockware = (req,res,next) => {
    if(block == true || block == undefined){
        return res.sendStatus(401);
    }
    next();
}

app.post('/getMyClaims', async(req,res) => {
    let {uid,idToken} = req.body;
    console.log(idToken.token)
    if(idToken.claims.type === 'customer'){
        block = true;
        console.log('deny')
    } else if(idToken.claims.type === 'admin'){
        block = false;
    } else {
        block = true;
    }
})

// admin only pages
app.get(['/seller','/add-product', '/add-product/:id'], blockware, (req,res) => {
    res.sendFile(path.join(staticPath, ''))
})

CodePudding user response:

You generally never want to store idTokens or jwt's server side. The purpose is for the client to send them along with each request like mentioned in one of the comments.

There is another problem with your code, is that it blindly trusts the token coming in. Wherever that token is being created (your code doesn't show where this is), you need to validate that the token isn't expired, and hasn't been tampered with by communicating with the service or verifying yourself with your server-side secret. Once it passes, only then you can trust the contents of the token and determine whether the user is a customer/admin/someone else.

See here for more info: https://medium.com/@mmoshikoo/simple-jwt-authentication-explanation-81e930a1a01f

  • Related