【问题标题】:Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权
【发布时间】:2021-08-12 15:51:24
【问题描述】:

Net 核心应用程序和反应 JavaScript。我正在做一些身份验证的概念证明。我从 github 克隆了一些示例应用程序并开发了 .net 核心 API 并尝试调用 API。我有以下代码在我的反应应用程序中调用 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>
      )
};

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

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

Configure 方法中的以下代码

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

我的 react 应用在 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,但仍然出现错误。有人可以帮我理解这个问题并解决这个问题吗?

【问题讨论】:

    标签: javascript reactjs asp.net-core cors


    【解决方案1】:

    您的 Cors 配置中缺少 Authorization 标头。可以使用以下选项:

    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

    【讨论】:

    • 感谢 marteendev 我在下面添加了代码 services.AddCors(options => { options.AddPolicy( "CorsPolicy", builder => { builder .WithOrigins("localhost:3000") .AllowAnyHeader() .AllowAnyMethod () .AllowCredentials(); }); }); 但努力工作
    猜你喜欢
    • 2016-05-15
    • 2017-10-20
    • 2017-10-28
    • 2017-10-15
    • 1970-01-01
    • 2016-04-24
    • 2019-02-21
    • 2017-06-23
    相关资源
    最近更新 更多