Azure-Samples/active-directory-javascript-nodejs-webapi-v2

How to get reason of token validation failure?

jefjos opened this issue · 4 comments

I have cloned this repo and running it locally. I have been able to run it successfully with valid token. For invalid tokens,, the API only returns 401, Unauthorized. How can I get the actual reason for failure like token expiry or invalid audience?
It would be great if you can point me to some code sample.

@jefjos the passport-azure-ad library can log the reasons to console if you set:

loggingNoPII: false 

in config.js.

However there is no feature in the library that would allow you to send these logs to the front-end (there might be other tools for that but I'm not aware of any). What you can do, though, is to set your own validation logic for reasons you care about, and send a response for them with the reason stated. If you actually look at the index.js, there we have:

        if (req.authInfo['scp'].split(" ").indexOf("demo.read") >= 0) {
            // Service relies on the name claim.  
            res.status(200).json({
                'request-for': 'access_token',
                'requested-by': req.authInfo['name'],
                'issued-by': req.authInfo['iss'],
                'issued-for': req.authInfo['aud'],
                'scope': req.authInfo['scp']
            });
        } else {
            console.log("Invalid Scope, 403");
            res.status(403).json({'error': 'insufficient_scope'}); 
        }

You could do something similar for validating the issuer, for example:

if (req.authInfo['iss'] != "https://sts.windows.net/{your-tenant-id}") {
        res.status(403).json({'error': 'invalid issuer'});
}

Thanks @derisen . But if I implement my own logic to do validation, then wouldn't that defeat the purpose of using the library?

@jefjos sorry I must have misunderstood you. You can pass a "custom callback" function to passport.authenticate(). Take a look at the documentation. The info parameter should tell you the reason for rejection, you can return this then as response.

Thanks @derisen ! This helps me.