Azure AD open BearerStrategy “TypeError: self.success is not a function”

安稳与你 提交于 2020-01-06 05:52:06

问题


I asked this at https://github.com/AzureAD/passport-azure-ad/issues/427 but have had no response. I feel it is a bug that is preventing me from completing my work so I am reaching farther and wider to get an answer. Is it something I'm doing or a bug?

I am writing the question different to I had before since I have done some more investigation in to the problem (I will indicate where the differences start).

Passport-Azure-AD version 4.1.0 - https://www.npmjs.com/package/passport-azure-ad#52-bearerstrategy

I have set this up from the documentation:

setup() {
    const findById = (id, fn) => {
        for (let i = 0, len = this.users.length; i < len; i++) {
            const user = this.users[i];
            if (user.sub === id) {
                logger.info('Found user: ', user);
                return fn(null, user);
            }
        }
        return fn(null, null);
    };

    this.bearerStrategy = new BearerStrategy(jwtOptions,
        (token: ITokenPayload, done: VerifyCallback) => {  
            findById(token.oid, (err, user) => {
                if (err) {
                    return done(err);
                }
                if (!user) {
                    // 'Auto-registration'
                    logger.info('User was added automatically as they were new. Their oid is: ', token.oid);
                    this.users.push(token);
                    this.owner = token.oid;
                    return done(null, token);
                }
                this.owner = token.oid;
                return done(null, user, token);
            });
        }
    );
    console.log(`setup bearerStrategy`);
}

The jwtOptions I use are:

The options are like this:

const jwtOptions = {
    identityMetadata: 'https://login.microsoftonline.com/xyz/v2.0/.well-known/openid-configuration',
    clientID: '0123456789',
    loggingLevel: 'info',
    loggingNoPII: false,
    passReqToCallback: false
};

And run authentication (from middlewhere) using the following:

authenticate(request: express.Request) {
    this.bearerStrategy.authenticate(request, {session: false});
}

NOTE That this is different to the doco since what they had doesn't work.

It fails on the line:

 return done(null, token);

With:

[2019-05-29T13:49:33.479] [INFO ] [AUTHSERVICE_LOGGER] - User was added automatically as they were new. Their oid is:  123

.../translateboard/node_modules/passport-azure-ad/lib/bearerstrategy.js:565
        return self.success(user, info);
                    ^
TypeError: self.success is not a function
    at verified (/Users/bbos/dev/dhs/translate/translateboard/node_modules/passport-azure-ad/lib/bearerstrategy.js:565:21)
    at findById (/Users/bbos/dev/dhs/translate/translateboard/server/src/services/AuthService.ts:106:32)
    at findById (/Users/bbos/dev/dhs/translate/translateboard/server/src/services/AuthService.ts:87:20)
    at Strategy.bearerStrategy.passport_azure_ad_1.BearerStrategy [as _verify] (/Users/bbos/dev/dhs/translate/translateboard/server/src/services/AuthService.ts:97:17)
    at jwt.verify (/Users/bbos/dev/dhs/translate/translateboard/node_modules/passport-azure-ad/lib/bearerstrategy.js:363:19)
    at /Users/bbos/dev/dhs/translate/translateboard/node_modules/passport-azure-ad/lib/jsonWebToken.js:80:16
    at process._tickCallback (internal/process/next_tick.js:61:11)

From here is different compared to original post

If I put a breakpoint in the code, the self Object in BearerStrategy.js where the error is:

{
  "name": "oauth-bearer",
  "_options": {
    "identityMetadata": "https://login.microsoftonline.com/xyz/v2.0/.well-known/openid-configuration",
    "clientID": "0123456789",
    "loggingLevel": "info",
    "loggingNoPII": false,
    "passReqToCallback": false,
    "clockSkew": 300,
    "validateIssuer": true,
    "allowMultiAudiencesInToken": false,
    "audience": [
      "1234",
      "spn:1234"
    ],
    "isB2C": false,
    "_isCommonEndpoint": false,
    "_verify" = (token, done) => {...},
    "__proto__" = Strategy(...,
  }
}

And under __proto__ are:

 authenticate = function authenticateStrategy(req, options) {
 constructor = function Strategy(options, verifyFn) {
 failWithLog = function(message) {
 jwtVerify = function jwtVerifyFunc(req, token, metadata, optionsToValidate, done) {
 loadMetadata = function(params, next) {

You can see there is no success in Passport-Azure-Ad. It does define a failWithLog https://github.com/AzureAD/passport-azure-ad/blob/e9684341920ac8ac41c55a1e7150d1765dced809/lib/bearerstrategy.js#L600 - did they forget to add the others?

Passport defines these others (https://github.com/jaredhanson/passport/blob/1c8ede35a334d672024e14234f023a87bdccaac2/lib/middleware/authenticate.js#L230) however they are in a closure and never exposed. Nor is the parent Strategy object that they are defined on. The only connection with the outside is through the exposed authenticate method https://github.com/jaredhanson/passport/blob/1c8ede35a334d672024e14234f023a87bdccaac2/lib/middleware/authenticate.js#L70

However as seen, Passport-Azure-Ad defines it's own authenticate method (https://github.com/AzureAD/passport-azure-ad/blob/e9684341920ac8ac41c55a1e7150d1765dced809/lib/bearerstrategy.js#L372) and never calls the passsport one.

To me it looks like it never worked.

Can anyone confirm or disagree?

I will update the post at https://github.com/AzureAD/passport-azure-ad/issues/427 to refer to this.

Next I am going to git bisect the repository to see if I can find a change where those missing methods used to be defined or something else that stands out.


回答1:


I can confirm that as my code was written it would never work. There were two main issues:

Pass parameters

As per my comment against the question, i neglected to provide information in the question since I didn't think it was relevant. But it is.

I am using TSED - TypeScript Express Decorators (https://tsed.io) and it replaces express middleware code like:

   server.get('/api/tasks', passport.authenticate('oauth-bearer', { session: false }), listTasks);

With an annotated middleware class - https://tsed.io/docs/middlewares.html

So now the call to passport.authenticate() is in the use() method like this as I showed before (THIS IS INCORRECT):

@OverrideMiddleware(AuthenticatedMiddleware)
export class UserAuthMiddleware implements IMiddleware {
    constructor(@Inject() private authService: AuthService) {
    }

    public use(
        @EndpointInfo() endpoint: EndpointMetadata,
        @Request() request: express.Request,
        @Response() response: express.Response,
        @Next() next: express.NextFunction
    ) {
        const options = endpoint.get(AuthenticatedMiddleware) || {};
        Passport.authenticate('oauth-bearer', {session: false});  // <-- WRONG
        if (!request.isAuthenticated()) {
            throw new Forbidden('Forbidden');
        }
        next();
    }
}

What I neglected to consider is that express middleware is passed the request object. So what I actually needed to have was:

        Passport.authenticate('oauth-bearer', {session: false})(request, response, next);  // <-- CORRECT

Must use Passport.use()

The documentation is misleading. Given I'm not overly savy with Passport I didn't think much about this.

The doco (http://www.passportjs.org/packages/passport-azure-ad/) (at 5.2.1.1 Sample using the BearerStrategy) says to use:

var bearerStrategy = new BearerStrategy(options,
  function(token, done) {
    log.info('verifying the user');
    log.info(token, 'was the token retreived');
    findById(token.oid, function(err, user) {
      if (err) {
        return done(err);
      }
      if (!user) {
        // "Auto-registration"
        log.info('User was added automatically as they were new. Their oid is: ', token.oid);
        users.push(token);
        owner = token.oid;
        return done(null, token);
      }
      owner = token.oid;
      return done(null, user, token);
    });
  }
);

I am aware that when other strategies are described (such as the 5.1 OIDCStrategy on the same page):

passport.use(new OIDCStrategy({
    identityMetadata: config.creds.identityMetadata,
    clientID: config.creds.clientID,
    ...
  },
  function(iss, sub, profile, accessToken, refreshToken, done) {
    ...
  }
));

They use passport.use. I thought about the difference (when i first saw it) for 1/2 a second and concluded that the AAD BearerStrategy handles things differently given the login is done by Azure using their msal.js library. And I didn't revisit this until Fix # 1 above didn't fix the problem.

I conclude that the TSED project needs to update their documentation / samples (I will do this for them); and the Passport Azure AD project needs to update their doco.

There are still some issues and I don't know who is at fault. I wrote about these at Passport-Azure-Ad in TSED framework seems to run asynchronously.



来源:https://stackoverflow.com/questions/56372349/azure-ad-open-bearerstrategy-typeerror-self-success-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!