我已根据本文创建了一个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:无法验证令牌
它说它无法验证令牌……我读到此: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);
}
}
}
有什么想法吗?
谢谢!
答案 0 :(得分:2)
正确配置BearerStrategy
引起了很多麻烦,所以我分享了有效的配置:
audience: 'https://graph.windows.net/'
道具放在您的策略配置中,CallWebApiProtectedAsync
方法,将resource
变量更改为string resource = "https://graph.windows.net/"
,因此,基本上,您是在要求使用Microsoft Graph API的权限(即使您没有不需要使用它,则需要将其放入config)。希望这会有所帮助:D