【问题标题】:CORS on .Net Core API returns 401 Unauthorized from axios request.Net Core API 上的 CORS 从 axios 请求返回 401 Unauthorized
【发布时间】:2018-04-28 04:57:40
【问题描述】:

我要做什么

我想从 React 前端向我的 API 发送 PATCH 请求。 API 使用 Identity Server 4 来验证请求。

发生了什么

请求有效并通过 POSTMAN 的控制器,但当它来自我的前端时它不会。当它来自 axios 请求时,它会抛出一个未经授权的响应。

附加说明,get 请求在前端工作得很好。 get 方法也受 Identity Server 保护

邮递员请求

http://localhost:90909/api/products/3434

    Headers =  { 
       Authorization: Bearer <token>
       Content-Type: application/json-patch+json
    }

    Body: 
    [
        {
         "op" : "replace",
         "path" : "/DESCRIPTION",
         "value" : "bruhhh"
        }
    ]

反应

 static update(data){
            let config = {
                data : [],
                headers: { 
                    'Authorization' : 'Bearer ' + data.access_token,
                    'Content-Type' : 'application/json-patch+json'           
                }     
            }

            config.data.push(
                    {
                     "op" : "replace",
                     "path" : "/DESCRIPTION",
                     "value" : "you da best"
                    }

            )

            return axios.patch(root + '/api/products/' + data.product.id, config);

    }

CORS 设置

services.AddCors(options =>
            {

                options.AddPolicy("JSClient", builder =>
                    builder.WithOrigins("http://localhost:9999")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });

日志

我启用了一些日志。这里有一些我已经posted from a few days ago

以下是我从现在得到的结果

预检

在CORS的飞行前检查期间似乎发生了以下错误。

System.InvalidOperationException: Writing to the response body is invalid for responses with status code 204.
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.HandleNonBodyResponseWrite()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.<WriteAsyncAwaited>d__199.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at InventoryApi.Utilities.AnotherLoggingMiddleware.<Invoke>d__3.MoveNext() in F:\My Site Projects\TestProjects\InventoryApi\AnotherLoggingMiddleware.cs:line 43
Exception thrown: 'System.InvalidOperationException' in InventoryApi.dll
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-11-15T03:42:56.0180842Z","tags":{"ai.internal.nodeName":"yay-PC","ai.operation.id":"0HL9BRASKOUFU:00000003","ai.application.ver":"1.0.0.0","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.operation.name":"OPTIONS /api/products/1020","ai.location.ip":"127.0.0.1","ai.cloud.roleInstance":"yay-PC"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"An unhandled exception has occurred while executing the request","severityLevel":"Error","properties":{"{OriginalFormat}":"An unhandled exception has occurred while executing the request","DeveloperMode":"true","CategoryName":"Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware","AspNetCoreEnvironment":"Development","Exception":"System.InvalidOperationException: Writing to the response body is invalid for responses with status code 204.\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.HandleNonBodyResponseWrite()\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.<WriteAsyncAwaited>d__199.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at InventoryApi.Utilities.AnotherLoggingMiddleware.<Invoke>d__3.MoveNext() in F:\\My Site Projects\\TestProjects\\InventoryApi\\AnotherLoggingMiddleware.cs:line 51\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()"}}}}
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:Error: An unhandled exception has occurred while executing the request

我检查了浏览器的网络选项卡,我得到一个 204,然后在预检请求后再次发送请求后立即得到一个 401。

这是 204

General
Request URL:http://localhost:90909/api/products/1020
Request Method:OPTIONS
Status Code:204 No Content
Remote Address:[::1]:90909
Referrer Policy:no-referrer-when-downgrade
Response:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:content-type
Access-Control-Allow-Methods:PATCH
Access-Control-Allow-Origin:http://localhost:99999
Date:Wed, 15 Nov 2017 04:24:24 GMT
Server:Kestrel
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RjpcTXkgU2l0ZSBQcm9qZWN0c1xUZXN0UHJvamVjdHasdfaseemVudG9yeUFwaVxhcGlccHJvZHVjdHNcMTAyMA==?=
Request Header:
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:PATCH
Connection:keep-alive
Host:localhost:90909
Origin:http://localhost:99999
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36

这是预检后请求的 401 响应

General
Request URL:http://localhost:90909/api/products/1020
Request Method:PATCH
Status Code:401 Unauthorized
Remote Address:[::1]:90909
Referrer Policy:no-referrer-when-downgrade
Response Header
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:99999
Content-Length:0
Date:Wed, 15 Nov 2017 04:24:24 GMT
Server:Kestrel
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RjpcTXkgU2l0ZSBQcm9qZWN0c1xUZXN0UHJvamVjdHasdfaseemVudG9yeUFwaVxhcGlccHJvZHVjdHNcMTAyMA==?=
Request Header
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Connection:keep-alive
Content-Length:850
Content-Type:application/json;charset=UTF-8
Host:localhost:90909
Origin:http://localhost:99999
Referer:http://localhost:99999/inventory/products
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Request Payload
{data: [{op: "replace", path: "/DESCRIPTION", value: "you da best"}], headers: {,…}}
data
:
[{op: "replace", path: "/DESCRIPTION", value: "you da best"}]
headers
:
{,…}

【问题讨论】:

    标签: cors .net-core axios identityserver3 identityserver4


    【解决方案1】:

    获取请求的服务器需要启用访问权限。

    例如在apache服务器上,在配置文件中添加Header set Access-Control-Allow-Origin:

    <Directory />
            Header set Access-Control-Allow-Origin "http://ipaddress:[port]"
    </Directory>
    

    origin 是从哪里提供 react 的......

    邮递员很可能被配置为允许任何来源访问...

    https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

    【讨论】:

    • 嘿,对不起,我忘了添加我的设置。但是我通过启用特定地址在我的 api 级别进行了设置。我编辑了帖子
    猜你喜欢
    • 2021-08-08
    • 2020-04-16
    • 2022-01-11
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 2019-08-03
    相关资源
    最近更新 更多