为什么缺少 MSAL.js return CORS header

Why does MSAL.js return CORS header is missing

MSAL.js 不断返回以下错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://webapi.azurewebsites.net/api/order. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://webapi.azurewebsites.net/api/order. (Reason: CORS request did not succeed).

我的 Back-end 托管在 Azure 中,并且还在 Azure Active Directory 中注册为 Web API。

Front-end 有一个 proxy.conf.json 并在 Azure Active Directory 中注册。

当我尝试访问 API(需要身份验证,我收到这些错误)时,我成功地验证并接收了 ID 和访问令牌。

我的proxy.conf.json看起来像:

{
  "/api/*": {
    "target": "https://webapi.azurewebsites.net",
    "secure": true,
    "changeOrigin": true,
    "pathRewrite": {
      "^/api": ""
    }
  }
}

我创建了一个 access_as_user 作用域 (api://[Application (client) ID]/access_as_user) 并将其设置在 SPA - Client App[ 的 ProtectedResource 中=13=]

export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
  const protectedResourceMap = new Map<string, Array<string>>();
  protectedResourceMap
    .set(auth.resources.graphApi.resourceUri, auth.resources.graphApi.resourceScopes)
    .set(auth.resources.Api.resourceUri, auth.resources.Api.resourceScopes);

  return {
    interactionType: InteractionType.Redirect,
    protectedResourceMap
  };
}

export function MSALGuardConfigFactory(): MsalGuardConfiguration {
  return {
    interactionType: InteractionType.Redirect,
    authRequest: {
      scopes: [...auth.resources.Api.resourceScopes]
    }
  };
}

只需在应用程序文件夹中创建一个 json 文件并在 app.module 中添加导入行即可访问 json 文件

import * as auth from '../app/auth-config.json';

auth json 文件的内容类似于:

"resources": {
      "graphApi": {
        "resourceUri": "https://graph.microsoft.com/v1.0/users",
        "resourceScopes": [ "User.Read", "openid", "profile" ]
      },
      "Api": {
        "resourceUri": "https://webapi.azurewebsites.net",
        "resourceScopes": [ "api://[Application (client) ID]/User.Read",
                            "api://[Application (client) ID]/access_as_user" ]
      }
    }