【问题标题】:401 Error - Call REST API secured with AZURE Active Directory (JavaScript Client)401 错误 - 调用使用 AZURE Active Directory(JavaScript 客户端)保护的 REST API
【发布时间】:2020-09-15 02:13:14
【问题描述】:

大家好,

我遇到了一个场景,我应该调用一个由 AZURE ACTIVE DIRECTORY 保护的 REST api。大多数代码运行良好,我也可以使用 myMSALObj.acquireTokenSilent 函数获取令牌。

当我使用该令牌发送 AJAX 调用时出现 401 错误,您可以看到以下代码

用户在我获得正确令牌的 Active Directory 中,我不知道为什么当我将该令牌发送到 rest-api 时我的 ajax 调用失败,请帮助

    
<script type="text/javascript">

    const msalConfig = {
        auth: {
            clientId: "94edf294-08ae-489f-8621-c6d98009afa8", 
            authority: "https://login.microsoftonline.com/c483b3c4-21a6-4c93-95ea-7436cf318a68",
            redirectUri: "https://localhost:44334/",
        },
        cache: {
            cacheLocation: "sessionStorage", // This configures where your cache will be stored
            storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
        }
    };

    const myMSALObj = new Msal.UserAgentApplication(msalConfig);

    function CallApi() {
        // Add scopes for the id token to be used at Microsoft identity platform endpoints.
        const loginRequest = {
            scopes: ["User.Read"],
        };

        myMSALObj.loginPopup(loginRequest)
            .then((loginResponse) => {

                const accessTokenRequest = {
                    scopes: ["api://8c2b0253-f9e8-442c-bccf-b4a8bbe73b59/access_as_user"]
                };

                myMSALObj.acquireTokenSilent(accessTokenRequest).then((accessTokenResponse) => {
                    var accessToken = accessTokenResponse.accessToken;
                    var apiEndpoint = "https://localhost:44387/api/hello";
                    var bearer = "Bearer " + accessToken;
                    console.log("accessToken = ", accessToken);
                    $.ajax({
                        url: apiEndpoint,
                        type: "GET",
                        beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", bearer) }
                    }).done(function (response) {
                        alert("SUCCESS");
                        console.log("response = ", JSON.stringify(response));
                    }).fail(function (err) {
                        console.error("Error Occurred");
                        console.log("error = ", JSON.stringify(err));
                    });

                })

            }).catch(function (error) {
                console.log(error);
            });
    }
</script>

新 API 代码的屏幕截图

JWT.ms(访问令牌)的屏幕截图

JWT Token 新截图

【问题讨论】:

  • 您是否将您的 API 暴露给客户端应用注册?
  • 使用jwt.ms 解析您的令牌并提供屏幕截图。您必须确保客户端应用程序请求的范围与令牌的预期接收者一致。检查你的aud,确保是你要调用的api,401的原因你可能使用了错误的token或者你使用了不属于该api的token来调用api。跨度>
  • @Purushothaman 我看不出您的代码有任何问题。我认为问题仍然出现在您的 apiEndpoint 中。您的 apiEndpoint 是自定义 api 吗?确保它是您的令牌接收者。
  • 您可以在此文档中找到在 web api 中实现身份验证和授权的详细信息。 docs.microsoft.com/en-us/azure/active-directory/develop/…

标签: javascript azure-active-directory http-status-code-401 rest


【解决方案1】:

您不应将appsettings.json file 中的client ID 设置为api app 的client id。它应该是您的client app 的客户端 ID。根据你提供的jwt分析图,我觉得应该是:94edf294- 08ae-489f-8621-c6xxxxxxx。

【讨论】:

  • 我今天试试
  • 我刚刚尝试并得到了同样的错误......我只是在这个问题上附加了一个新的屏幕截图。请检查
  • @Imran 您可能误解了我的意思,我的意思是您应该将 appsettings.json 文件中的 client id 更改为:94edf294- 08ae-489f-8621-c6xxxxxxx.
  • 是的,我更改了 appsettings.json 中的ClientId 文件,然后附上了显示新 ClientId 的 JWT 令牌的新屏幕截图。
【解决方案2】:

我的 startup.cs 文件中缺少后续调用

app.UseAuthentication();

感谢你们的帮助

特别 - @Carl Zhao、@Purushothaman @Rass Masood

【讨论】:

    猜你喜欢
    • 2017-08-29
    • 2016-08-14
    • 1970-01-01
    • 2016-03-28
    • 2017-04-20
    • 1970-01-01
    • 2015-10-29
    • 2021-02-24
    • 2017-11-05
    相关资源
    最近更新 更多