gpt4 book ai didi

javascript - 如何获取自定义 Azure 应用程序 API 的有效访问 token ? (MSAL.js)

转载 作者:行者123 更新时间:2023-12-03 02:19:46 25 4
gpt4 key购买 nike

我正在尝试构建一个小型网络应用程序,它可以显示我的名字、我的日程安排和我的学校成绩。

我的学校主要使用 Microsoft 的服务,这让我想到在我的项目中使用他们的 Azure API 端点(用于时间表和成绩)。

我有权在 Azure 门户中创建应用程序注册,因此我这样做了,并让它可以使用我的学生电子邮件登录。我还尝试获取 Microsoft Graph API,效果非常好。

但是,当我尝试获取成绩端点时,它返回 401 未经授权错误。我猜这与范围有关,但我不确定。事实证明,我的访问 token 对于这些 API 端点无效。

所以我的问题是,如何获得对这些 API 有效的访问 token ?或者说有可能吗? 请记住,它们是 Azure 门户中单独的应用程序注册,我只能编辑我自己的应用程序,而不能编辑我学校的应用程序。

这是我的 JavaScript 文件,其中包含一些注释:

const config = {
auth: {
clientId: "my_client_id_is_here",
authority: "https://login.microsoftonline.com/my_tenant_id_is_here",
redirectUri: "localhost"
}
};

async function login() {

console.log("Started..")

var client = new Msal.UserAgentApplication(config);

var request = {
scopes: [ 'User.Read' ]
};

let loginResponse = await client.loginPopup(request);
console.dir(loginResponse);

let tokenResponse = await client.acquireTokenSilent(request);
console.dir(tokenResponse);

// User REQUEST - Here I fetch the Graph API for some profile information, which works fine and writes it to the HTML perfectly.

let req = await fetch("https://graph.microsoft.com/v1.0/me/", {
headers: {
"Authorization": "Bearer " + tokenResponse.accessToken
}
});

let json = await req.json();

console.log(json);

document.write("Logged in as " + json.displayName);
document.write("<br>" + json.mail);
document.write("<br>" + json.jobTitle + " " + json.officeLocation);

// School Grades REQUEST - this is the part where I'm trying to fetch my School Grades, but it's not working since it gives me a 401 error..

let gradesReq = await fetch("https://myschool.azurewebsites.net/API/Grades/GetGrades", {
"headers": {
"authorization": "Bearer " + tokenResponse.accessToken
}
});

try {
let gradesJson = await gradesReq.json();
console.log(gradesJson);
} catch (err) {
document.write("An error occured while trying to get the school grades..")
}
}```

最佳答案

你的想法是正确的。您收到此错误的原因是您在 API 中使用了为不同范围 (User.Read) 获取的访问 token 。

修复相当简单。

您要做的就是首先使用 Azure AD 保护您的 API。您可能会发现此链接有助于实现此功能:https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-overview .

完成此操作后,您所需要做的就是获取 API 的 token 。在这种情况下,您的范围代码将类似于以下内容:

var request = {
scopes: [ 'api://<your-application-id>/.default' ]
};

一旦您获取此范围的 token 并将其与您的 API 一起使用,您就不应该收到您所收到的 401 异常。

关于javascript - 如何获取自定义 Azure 应用程序 API 的有效访问 token ? (MSAL.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69562175/

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