Why is my SPA, which is calling my WebAPI, using Azure Active Directory, receiving “Authorization has been denied for this request.”?

孤人 提交于 2019-12-11 06:06:57

问题


I have a local SPA client (based on https://docs.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-javascript-spa)

Then there is a WebAPI service. (based on https://github.com/Azure-Samples/active-directory-dotnet-native-desktop)

The service should only respond to authenticated and authorized clients. To this end I am using Azure active directory (AD).

Here a picture of how the 3 parts are linked. Numbers refer to the order of the calls.

Although Azure AD seems to return an access token to the client, and the client sends the access token to the service in the header, the service responds with

Authorization has been denied for this request

Question Why does this happen? My gut feeling is that my locally running service is somehow „not talking to Azure AD“.

Details

Both the client and the service are „app registrations“ in Azure AD.

The service exposes an API.

The service configuration has the „tenant“ and the „audience“. Seems like too little configuration.

The client has API permissions.

The client configuration has the client app registration ID.

The client essentially consists of a button to sign in and a button to get a list of todos from an API. Below a screenshot of the client, and the Firefox developer tools with the login page.

When the client starts, I first need to authenticate with Azure AD. The client receives the access token. Below the response.

When I press „Get Todos“ the service is called with the access token but the response is 401.

The code for getting the todo list

function getTodos() {

    myMSALObj.acquireTokenPopup(requestObj).then(function (tokenResponse) {

        var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                console.log("success");                 
            } else {
                console.log("failure");
            }
        }
        const apiUrl = "https://localhost:44321/api/todolist";
        xmlHttp.open("GET", apiUrl, true); // true for asynchronous

        //No, the API sends back this header (to indicate that cross origin requests are allowed). xmlHttp.setRequestHeader('Access-Control-Allow-Origin', 'Bearer ' + tokenResponse.accessToken);

        xmlHttp.setRequestHeader('Authorization', 'Bearer ' + tokenResponse.accessToken);
        xmlHttp.send();

    }).catch(function (error) {
        console.log(error);
    });

}

来源:https://stackoverflow.com/questions/56937160/why-is-my-spa-which-is-calling-my-webapi-using-azure-active-directory-receivi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!