2

我在这篇文章之后创建了一个 Web API: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);

但是当我尝试调用 api 我得到这个错误: Strategy.prototype.jwtVerify: cannot verify token

它说它无法验证令牌......我读到这个:https ://github.com/AzureAD/passport-azure-ad/issues/373我添加了观众属性,但它不起作用:

以下是护照的选项:

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`
};

这个想法是从客户端或其他 Web 应用程序调用经过身份验证的 API……这是我正在使用的方法:

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);
            }
        }
    }

有什么想法吗?

谢谢!

4

1 回答 1

2

正确配置会引起很多麻烦BearerStrategy,因此我与有效配置共享:

  • 服务器端,把audience: 'https://graph.windows.net/'道具放在你的策略配置上,
  • 在客户端,在您的CallWebApiProtectedAsync方法示例中,将resource变量更改为string resource = "https://graph.windows.net/",所以基本上您要求使用 Microsoft Graph API 的权限(即使您不需要使用它,也需要将其放入 config )。

希望这会有所帮助:D

于 2018-12-28T16:52:40.073 回答