Search code examples
node.jsoauth-2.0postmanaccess-token

Access token revocation implementation in OAuth 2 (Node js)


I am using oAuth 2 package modified by him -> https://github.com/pedroetb/node-oauth2-server-mongo-example

I am stuck in the token revocation part. How to logout a user by calling revoke token?

var revokeToken = function(token, callback) {

    tokenModel.deleteOne({
        refreshToken: token.refreshToken
    }).exec((function(callback, err, results) {

        var deleteSuccess = results && results.deletedCount === 1;

        if (!deleteSuccess) {
            console.error('Token not deleted');
        }

        callback(err, deleteSuccess);
    }).bind(null, callback));
};

The revoke token is done but I am not understanding how to call this one? do I have to do something like this?

app.post('/logout', revokeToken);

Postman screenshot:

Get token: logout:


Solution

  • From the node-oauth2-server library, only three APIs call available. it are oauth.authorize(), oauth.authenticate() and oauth.token(), there are no revoke_token() API but we can workaround to revoke token by refresh token().

    This is my approaches by refresh token method. Adding this code in app.js of example

    app.post('/logout', revokeToken, function(req, res) {
        res.send('Congratulations, you are logged out!');
    });
    
    function revokeToken(req, res) {
        var request = new Request(req);
        var response = new Response(res);
        return app.oauth.token(request, response)
            .then(function(token) {
                token.accessToken = '';
                token.accessTokenExpiresAt = '';
                token.refreshToken = '';
                token.refreshTokenExpiresAt = '';
                res.json(token);
            }).catch(function(err) {
                res.status(err.code || 500).json(err);
            });
    }
    

    Demo

    1. Run example

    npm start
    

    2. Ready to assign to Postman variable

    enter image description here

    3. Get Access token and Refresh Token

    enter image description here

    4. Check Valid access token

    enter image description here

    5. Logout - using refresh token and revoke the access token

    enter image description here

    6. Check valid access token - access-token no more valid due to revoked by refresh token.

    enter image description here