azure - 获取受保护的 Azure ADv2 Rest Api 的令牌
问题描述
我使用 Visual Studio 和向导为受保护的 api 创建了一个 WebApi。
结果是 Azure 门户中的一个新应用程序,以及一个配置文件 jsonconfig(我使用的是 netcore 2.2)
web api非常简单,部分代码是
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
现在我正在尝试使用下一个代码获取调用 api 的令牌
var msalConfig = {
auth: {
clientId: '83a8a6ee-afd5-41d3-92bd-2a6352cff7da', //This is your client ID
authority: "https://login.microsoftonline.com/d7124a8f-3301-4c72-9231-4bb39d8b95a3" //This is your tenant info
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
}
};
和呼唤
var requestObj2 = {
scopes:["https://xxxxxx.com/Test2019/user_impersonation"]
};
var myMSALObj = new Msal.UserAgentApplication(msalConfig);
function signIn() {
myMSALObj.loginPopup(requestObj).then(function (loginResponse) {
//Successful login
showWelcomeMessage();
//Call MS Graph using the token in the response
acquireTokenPopupAndCallMSGraph();
}).catch(function (error) {
//Please check the console for errors
console.log(error);
});
}
最后
function acquireTokenPopupAndCallMSGraph() {
//Always start with acquireTokenSilent to obtain a token in the signed in user from cache
myMSALObj.acquireTokenSilent(requestObj2).then(function (tokenResponse) {
console.log(tokenResponse.accessToken);
alert('autenticado');
callMSGraph(graphConfig.graphMeEndpoint, tokenResponse.accessToken, graphAPICallback);
}).catch(function (error) {
console.log(error);
// Upon acquireTokenSilent failure (due to consent or interaction or login required ONLY)
// Call acquireTokenPopup(popup window)
if (requiresInteraction(error.errorCode)) {
myMSALObj.acquireTokenPopup(requestObj).then(function (tokenResponse) {
callMSGraph(graphConfig.graphMeEndpoint, tokenResponse.accessToken, graphAPICallback);
}).catch(function (error) {
console.log(error);
});
}
});
}
一切正常,但在授权标头 =“Bearer Token”中的邮递员中使用时生成的令牌
不工作。
请就如何获得令牌提供任何建议.. :(
谢谢!
解决方案
您获取访问令牌的方式是正确的。将范围的值替换为并重scopes:["83a8a6ee-afd5-41d3-92bd-2a6352cff7da/.default"]
试。
如果这仍然不起作用,请在此处粘贴错误消息。
这是一个关于使用访问令牌调用后端 Web api的完整示例。
推荐阅读
- sql-server - 如何在 SQL Server 中使用多个 CHARINDEX 函数?
- chatbot - 具有相同同义词的 Diaglogflow 实体的不同值可以让机器人要求澄清吗?
- php - 从 WP_Query 循环中的产品变体中获取 Woocommerce 产品类别
- javascript - 无需选择选择 ID。获取价值
- angular-reactive-forms - 角度反应形式的错误检查
- qt - Qt Creator 中的“Qt Embedded”字体
- php - Laravel - 所有默认验证错误消息的列表
- javascript - 如何在页面上克隆或添加多个 ck 编辑器
- javascript - 等待多个非嵌套回调
- tfs - 在 TFS 构建中使用 ClickOnce-Manifest 构建错误