首页 > 解决方案 > 获取受保护的 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”中的邮递员中使用时生成的令牌

不工作。

请就如何获得令牌提供任何建议.. :(

谢谢!

标签: azureazure-active-directorymsal

解决方案


您获取访问令牌的方式是正确的。将范围的值替换为并重scopes:["83a8a6ee-afd5-41d3-92bd-2a6352cff7da/.default"]试。

如果这仍然不起作用,请在此处粘贴错误消息。

这是一个关于使用访问令牌调用后端 Web api的完整示例。


推荐阅读