gpt4 book ai didi

node.js - Passport azure 广告 Strategy.prototype.jwtVerify : cannot verify token

转载 作者:搜寻专家 更新时间:2023-11-01 00:50:26 25 4
gpt4 key购买 nike

我按照本文创建了一个 Web API:https://learn.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: 无法验证 token

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

以下是 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`
};

这个想法是从客户端或其他 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);
}
}
}

有什么想法吗?

谢谢!

最佳答案

正确配置 BearerStrategy 会带来很多麻烦,因此我分享有效的配置:

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

希望这有帮助:D

关于node.js - Passport azure 广告 Strategy.prototype.jwtVerify : cannot verify token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52582547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com