passport-azure-ad,它是否解析并验证令牌?

passport-azure-ad, does it parse & validate token?

我的 MEAN 堆栈应用程序正在使用 Azure AD 进行身份验证。我正在使用 “passport-azure-ad” 模块进行网络 api 身份验证。基于 我理解

If user is already authenticated by client (UI) then for every API call, client will also send token to the server. And then on the server we can use bearer strategy to “Authorize” user’s access to API.

现在在我的场景中,我只想确保用户已通过身份验证,如果他通过身份验证,则允许他访问 API。

问题
1. 当服务器执行"passport.authenticate('oauth-bearer')"方法时,passport-azure-ad会自动解析并验证从客户端收到的token或者我需要任何额外的步骤吗?
2. 当它无法验证令牌或者令牌是坏的或被欺骗时会发生什么?

这是我的完整代码
AzureAuthenticationService.js

    "use strict";
    var passport = require('passport');
    var OIDCBearerStrategy = require('passport-azure-ad').BearerStrategy;

    var options = {      
        identityMetadata: 'https://login.microsoftonline.com/tenantid/.well-known/openid-configuration',   
        validateIssuer: true, 
        passReqToCallback: false,
        loggingLevel: 'error' 
    };

    function configure(app) {    
        app.use(passport.initialize());
        app.use(passport.session());  

        passport.use(new OIDCBearerStrategy(options,
            function(token, done) {
               //is there anything else i need to do here?
               return done(null, token.unique_name, token);            
            })); 

             passport.serializeUser(function (user, done) {
                    done(null, user);
             });

            passport.deserializeUser(function (id, done) {
                done(null, id);
            });         
    }

    function authenticate(req, res, next) {
        //is there anything else i need to do here?
        passport.authenticate('oauth-bearer')(req, res, next);
    }

server.js
'UserService' 下面是我用来从数据库中获取用户的,我想保护那个 API 调用

        "use strict";

    var authentication = require('./AzureAuthenticationService');
    var userService = require('./UserService');

    // Initialize server
    var express = require('express');
    var app = exports.app = express();
    authentication.configure(app);

    // Set routes
    app.get('/api/users',authentication.authenticate,userService.getUsers);

我是 passport-azure-ad 的维护者。要回答您的问题,是的,它将为您验证令牌。它使用代码中对 jwtVerify 的调用来执行此操作。 You can see where this starts here。它将使用在您的配置中的元数据端点处找到的密钥来解密令牌。

如果验证不成功,您将从代码中看到错误,如上文和此处引用的那样:

jwt.verify(token, PEMkey, options, function(err, token) {
            if (err) {
                if (err instanceof jwt.TokenExpiredError) {
                    log.warn("Access token expired");
                    done(null, false, 'The access token expired');
                } else if (err instanceof jwt.JsonWebTokenError) {
                    log.warn("An error was received validating the token", err.message);
                    done(null, false, util.format('Invalid token (%s)', err.message));
                } else {
                    done(err, false);
                }

让我知道这是否有帮助,如果有帮助,请标记为已回答。谢谢!