2017-11-15 4 views
0

Was ich versuche, eine PATCH Anfrage an meine API senden von einem Reagieren Frontend zu tunCORS auf .Net Core-API gibt 401 Unauthorized von axios Anfrage

ich will. Die API verwendet Identity Server 4 zur Validierung der Anfrage.

Was

Die Anforderung arbeitet passiert und geht durch die Steuerung von POSTMAN aber es funktioniert nicht, wenn es von meinem Frontend kommen wird. Es löst eine nicht autorisierte Antwort aus, wenn es von der Axios-Anfrage kommt.

Zusätzliche Anmerkung, die Get-Anfrage funktioniert super vom Frontend. Die Get-Methoden werden auch von Identity Server

Postman Anfrage

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); 

    } 

services.AddCors(options => 
      { 

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

CORS-Setup 0

Protokolle

Ich habe ein paar Protokolle aktiviert. Hier einige, dass ich schon posted from a few days ago

Und unten ist das, was ich von jetzt bekam

Preflight

Der folgende Fehler scheint während der Pre Flight-Check von CORS zu passieren.

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 

überprüfte ich die Registerkarte Netzwerk des Browsers und ich bekomme eine 204 und erhalten dann sofort einen 401, nachdem er die Anforderung erneut nach dem Preflight-Anforderung sendet.

Dies ist der 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 

Dies ist die 401-Antwort für die Anfrage nach dem Preflight

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 
: 
{,…} 

Antwort

0

Der Server, der die Anfrage-Zugriff aktiviert haben muss erhält.

Zum Beispiel auf einem Apache-Server, in der Konfigurationsdatei hinzufügen, die Header-Set Access-Control-Allow- Herkunft:

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

Wo der Ursprung ist überall dort, wo reagiert aus wird serviert. ...

Postman, höchstwahrscheinlich, ist so konfiguriert, jeder Herkunft den Zugang zu ermöglichen ...

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

+0

Hey, sorry ich vergaß mein Setup hinzuzufügen. Aber ich hatte dieses Setup auf meinem API-Level, indem ich die spezifische Adresse aktivierte. Ich habe den Beitrag bearbeitet – gdubs

Verwandte Themen