2
votes

I’ve created a web API following this article: https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v1-nodejs-webapi

const restify = require('restify'),
    restifyPlugins = require('restify-plugins'),
    config = require('./config'),
    serverPort = process.env.PORT || config.serverPort,
    passport = require('passport'),
    BearerStrategy = require('passport-azure-ad').BearerStrategy,
    authenticatedUserTokens = [];

const server = restify.createServer({ name: 'Azure Active Directroy with Node.js Demo' });

const authenticationStrategy = new BearerStrategy(config.credentials, (token, done) => {
    let currentUser = null;
    let userToken = authenticatedUserTokens.find((user) => {
        currentUser = user;
        user.sub === token.sub;
    });

    if (!userToken) {
        authenticatedUserTokens.push(token);
    }

    return done(null, currentUser, token);
});

passport.use(authenticationStrategy);

server.use(restifyPlugins.authorizationParser());
server.use(passport.initialize());
server.use(passport.session());

server.get('/api', (req, res, next) => {
    res.send(200, 'Try: curl -isS -X GET http://127.0.0.1:3000/api');
    next();
});

server.get('/authenticated', passport.authenticate('oauth-bearer', { session: false }), (req, res, next) => {
    res.json({ message: 'response form authenticated API endpoint' });
    return next();
});

server.listen(serverPort);

But when I try to call the api I get this error: Strategy.prototype.jwtVerify: cannot verify token

It says that it cannot verify the token… I read this: https://github.com/AzureAD/passport-azure-ad/issues/373 and I added the audience property but it doesn’t work:

Here is the options for passport:

const tenantName = "MY_TENANT",
    clientID = "CLIENT_ID",
    serverPort = 3000;

module.exports.serverPort = serverPort;

module.exports.credentials = {
    identityMetadata: `https://login.microsoftonline.com/${tenantName}.onmicrosoft.com/v2.0/.well-known/openid-configuration`,
    //identityMetadata: `https://login.microsoftonline.com/${tenantName}.onmicrosoft.com/.well-known/openid-configuration`,
    clientID: clientID,
    audience: `https://${tenantName}.onmicrosoft.com/9fc847b6-92d0-4739-9eb1-6201752d6af1`
};

The idea is to call the authenticated API from a client or other web application… here is the method that I’m using:

static async Task CallWebApiProtectedAsync()
        {
            var parameters = new PlatformParameters(PromptBehavior.Always);

            string authority = "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/token";
            string resource = "9fc847b6-92d0-4739-9eb1-6201752d6af1"; //Web API Client Id
            string clientId = "0564e082-e1f3-4506-9263-d2171516f934";
            string clientSecret = "CLIENT_SECRET";
            string redirectUri = "http://clientAPIADD";

            try
            {
                var authContext = new AuthenticationContext(authority);
                //var token = await authContext.AcquireTokenAsync(resource, clientId, new Uri(redirectUri), parameters);
                var clientCredential = new ClientCredential(clientId, clientSecret);
                var token = await authContext.AcquireTokenAsync(resource,clientCredential);

                var authHeader = token.CreateAuthorizationHeader();

                Console.WriteLine($"AccessTokenType: {token.AccessTokenType} AccessToken:{token.AccessToken}");

                var client = new HttpClient();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.AccessTokenType, token.AccessToken);
                var requestURI = new Uri("http://localhost:3000/authenticated");
                Console.WriteLine($"Reading values from '{requestURI}'.");
                HttpResponseMessage httpResponse = await client.GetAsync(requestURI);
                Console.WriteLine($"HTTP Status Code: '{httpResponse.StatusCode.ToString()}'");
                Console.WriteLine($"HTTP Response: '{httpResponse.ToString()}'");
                string responseString = await httpResponse.Content.ReadAsStringAsync();
                var json = JsonConvert.DeserializeObject(responseString);
                Console.WriteLine($"JSON Response: {json}");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception in CallWebApirotectedAsync(): " + ex.Message);
            }
        }
    }

Any thoughts?

Thanks!

1

1 Answers

2
votes

It's causing a lot of headache to configure BearerStrategy properly, so I'm sharing with valid configuration:

  • Server side, put audience: 'https://graph.windows.net/' prop on your strategy configuration,
  • On client side, in your example in CallWebApiProtectedAsync method, change resource variable to string resource = "https://graph.windows.net/", so basicaly you're asking permissions to use Microsoft Graph API ( even if you don't need to use it, you need to put it into config ).

Hope this helps :D