为什么 MSAL loginPopup 响应“应用程序客户端请求资源上不存在的范围”?

Why does MSAL loginPopup respond with „the application client asked for scope that doesn't exist on the resource“?

(问题继续:Why is my SPA, which is calling my WebAPI, using Azure Active Directory, receiving "Authorization has been denied for this request."?

我的客户端 SPA 正在尝试调用受保护的 WebAPI(服务)。客户端使用 MSAL(微软身份验证库)。问题发生在调用 API 之前,即在下图中 1 和 2 之间的某处。

这是客户

<!DOCTYPE html>
<html>
<head>
    <title>Quickstart for MSAL JS</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>
    <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.2/js/msal.js"></script>
</head>
<body>
    <div class="container">
        <div>
            <button id="GetTodos" onclick="getTodos()">Get Todos</button>
        </div>
    </div>
    <script>

        var msalConfig = {
            auth: {
                clientId: 'xxxxxxxxxxxxxxxxxxxxxxx2427', 
                authority: "https://login.microsoftonline.com/my.tenant"
            },
            cache: {
                cacheLocation: "sessionStorage",
                storeAuthStateInCookie: true
            }
        };


        var requestObj = {
            // scopes: ["user.read"]
            scopes: ["access_as_user"]
        };

        var myMSALObj = new Msal.UserAgentApplication(msalConfig);

        myMSALObj.handleRedirectCallback(authRedirectCallBack);

        function getTodos() {
            console.log("getTodos ...");

            myMSALObj.loginPopup(requestObj)
                .then(response => {
                    myMSALObj.acquireTokenPopup(requestObj).then(function (tokenResponse) {

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

                    }).catch(function (error) {
                        console.log(error);
                    });
                })
                .catch(err => {
                    // handle error
                    console.log("login popup failed.", err);
                });
        }


        function authRedirectCallBack(error, response) {
            console.log('authRedirectCallBack');
            if (error) {
                console.log(error);
            } else {
                if (response.tokenType === "access_token") {
                    console.log("response.tokenType === access_token");
                } else {
                    console.log("token type is:" + response.tokenType);
                }
            }
        }

    </script>
</body>
</html>

客户端和服务都是在 Azure Active Directory 上注册的应用程序

客户端具有 API 访问服务的权限。

并且该服务确实公开了范围为 access_as_user

的 API

然而调用

myMSALObj.loginPopup(requestObj)

原因

ServerError: "AADSTS650053: The application 'ClientSPA' asked for scope 'access_as_user' that doesn't exist on the resource '00000003-0000-0000-c000-000000000000'.

并且在使用 Chrome 时我收到此消息

进一步调查

我不要求范围“access_as_user”,而是要求范围“user.read” 这给了我一个访问令牌。但这会导致 WebAPI 响应

Authorization has been denied for this request

当我解码访问令牌时,我看到观众是 https://graph.microsoft.com. But I am expecting the audience to be „https://my.tenant/TodoListService-NativeDotNet”。请参见下图(混淆线确实包含特定于我的用户和我注册的应用程序的信息)

问题

  1. 资源'00000003-0000-0000-c000-000000000000'的ID是从哪里来的(报错信息中有提到)?它不是客户端或服务的应用程序 ID。

  2. 我在 Azure Active Directory 或客户端的配置中做错了什么?

  3. CORS 会是个问题吗?我已经设置了允许 CORS 的服务。

范围应包括公开资源的标识符(应用程序 ID URI)。您可以通过转到 "Expose an API" -> 编辑范围 -> 复制顶部的标签来找到完整的值...

var requestObj = {
    // scopes: ["https://graph.microsoft.com/user.read"]
    scopes: ["https://ServiceWebAPI/TodoListService-NativeDotNet-access_as_user"]
};

在此处进一步阅读各个范围:https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#requesting-individual-user-consent