Skip to content

Token Based Auth

Davey edited this page Jul 11, 2022 · 1 revision

Token Based What?

As explained on the previous page, we now know what Bearer tokens are and what kind of information they can contain. But how did I make it work in the application.

In each secure API url the following function is executed:

const validToken = await network.validateToken(req,oAuth2Client,OAuth2Data);

And if it returns a false response the user gets a 401 error which means he is unauthorized to execute this or he is not logged in.

    if(!validToken) {
        res.status(401).json({ message: 'invalid token'} );
        return;
    }

But what does the function "validateToken" do?

exports.validateToken = async function (req,oAuth2Client,OAuth2Data) {

    var token = req.headers['authorization']; // put token in header as authorization

    if(!token) {
        return false; // return false so we can give the 401 response
    }

    token = token.replace('Bearer ','); 
    
    console.log(token);

    try {
        let ticket = await oAuth2Client.verifyIdToken({ idToken:token, audience: OAuth2Data.web.client_id });
        return true;
    } catch(error) {
        console.error('error',error);
        return false;
    }
}

This function connects to the Google API where I have filled data like authed url and callback. This allows me to get the token back from Google and use it in the application.

Google OAuth instance:

const oAuth2Client = new google.auth.OAuth2(OAuth2Data.web.client_id, 
    OAuth2Data.web.client_secret,
    OAuth2Data.web.redirect_uris[0]);
Clone this wiki locally