簡體   English   中英

預檢響應中的 Access-Control-Allow-Headers 不允許請求 header 字段授權

[英]Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response

網絡核心應用程序和反應 JavaScript。 我正在做一些身份驗證的概念證明。 我已經從 github 克隆了一些示例應用程序,並開發了 .net 核心 API 並嘗試調用 ZDB974238714CA3ACE4DA8ACE4634。 我有以下代碼在我的反應應用程序中調用 API。

這是 fetch.js

export const callApiWithToken = async(accessToken, apiEndpoint) => {
    debugger;
    const headers = new Headers();
    const bearer = `Bearer ${accessToken}`;

    headers.append("Authorization", bearer);
    const options = {
        method: "GET",
        headers: headers
    };

    return fetch(apiEndpoint, options)
        .then(response => response.json())
        .catch(error => console.log(error));
}

下面是Hello.jsx

import { useEffect, useState } from "react";

import { MsalAuthenticationTemplate, useMsal, useAccount } from "@azure/msal-react";
import { InteractionRequiredAuthError, InteractionType } from "@azure/msal-browser";

import { loginRequest, protectedResources } from "../authConfig";
import { callApiWithToken } from "../fetch";
import { HelloData } from "../components/DataDisplay";

const HelloContent = () => {
   
    const { instance, accounts, inProgress } = useMsal();
    const account = useAccount(accounts[0] || {});
    const [helloData, setHelloData] = useState(null);

    useEffect(() => {
        if (account && inProgress === "none" && !helloData) {
            instance.acquireTokenSilent({
                scopes: protectedResources.apiHello.scopes,
                account: account
            }).then((response) => {
                callApiWithToken(response.accessToken, protectedResources.apiHello.endpoint)
                    .then(response => setHelloData(response));
            }).catch((error) => {
                // in case if silent token acquisition fails, fallback to an interactive method
                if (error instanceof InteractionRequiredAuthError) {
                    if (account && inProgress === "none") {
                        instance.acquireTokenPopup({
                            scopes: protectedResources.apiHello.scopes,
                        }).then((response) => {
                            callApiWithToken(response.accessToken, protectedResources.apiHello.endpoint)
                                .then(response => setHelloData(response));
                        }).catch(error => console.log(error));
                    }
                }
            });
        }
    }, [account, inProgress, instance]);
  
    return (
        <>
            { helloData ? <HelloData helloData={helloData} /> : null }
        </>
    );
};
export const Hello = () => {
    const authRequest = {
        ...loginRequest
    };

    return (
        <MsalAuthenticationTemplate 
            interactionType={InteractionType.Redirect} 
            authenticationRequest={authRequest}
        >
            <HelloContent />
        </MsalAuthenticationTemplate>
      )
};

然后我在 my.Net 核心應用程序中配置了 CORS。 下面的代碼在 ConfigureServices 方法中。

services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                                  builder =>
                                  {
                                      builder.WithOrigins("https://localhost:3000");
                                  });
            });

配置方法中的以下代碼

app.UseCors(MyAllowSpecificOrigins);
            app.UseAuthentication();

我的反應應用程序在 https://localhost:3000 和 API 應用程序在 https://localhost:44367/weatherforecast 運行

當我運行應用程序時,我看到以下錯誤

Access to fetch at 'https://localhost:44367/weatherforecast' from origin 'https://localhost:3000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

我在.Net核心中添加了CORS,但仍然出現錯誤。 有人可以幫我理解這個問題並解決這個問題嗎?

您在 Cors 配置中缺少Authorization header。 可以使用以下選項:

options.AddPolicy("MyAllowHeadersPolicy",
    builder =>
    {
        // requires using Microsoft.Net.Http.Headers;
        builder.WithOrigins("https://localhost:3000")
               .WithHeaders(HeaderNames.Authorization);
    });

或者:

options.AddPolicy("MyAllowAllHeadersPolicy",
    builder =>
    {
        builder.WithOrigins("https://localhost:3000")
               .AllowAnyHeader();
    });

文檔: https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM