获取受保护的Azure ADv2 Rest Api的令牌

时间:2019-06-20 08:15:22

标签: azure azure-active-directory msal

我使用Visual Studio和向导为受保护的api创建一个WebApi。

结果是Azure门户中有一个新应用程序,还有一个配置文件jsonconfig(我正在使用netcore 2.2)

网络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”中使用时生成的令牌

不起作用。

请获取有关如何获取令牌的任何建议。.:(

谢谢!

1 个答案:

答案 0 :(得分:0)

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

如果仍然无法解决,请在此处粘贴错误消息。

这里是complete example,与使用访问令牌调用后端网络api有关。