2

I'm trying to send a request like this:

var req = new HttpRequestMessage(HttpMethod.Get, requestUri);
req.SetBrowserRequestMode(BrowserRequestMode.NoCors);
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
var resp = await httpClient.SendAsync(req, cancellationToken);

I see that authrozation header that I set does not send. But if I remove the 2nd line it will send. I need to set the 2nd line.

Why it should not send authorization when setting BrowserRequestMode to NoCors?

Aliaaa
  • 1,590
  • 2
  • 16
  • 37
  • See following : https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0#how-cors-works – jdweng Jan 17 '21 at 14:52

2 Answers2

2

from msdn web docs :

no-cors — Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers.

Simple headers are what we call CORS-safelisted request headers like :

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type

Authorization header is not being sent because in your second line you're preventing that header from being sent by enabling cors. I don't know if you're doing that for some purpose or not but I think it's a cors related thing , your code is correct. There are plenty of answers explaining CORS out there.

Helix112
  • 305
  • 3
  • 12
  • So this means that calling 3rd party APIs must be "tunneled" through your own backend any time if they need such a header for e.g. authentification? – feffe Dec 22 '21 at 13:30
-1

According MDN - no-cors — Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers. Bearer is not included in the simple headers list.

And I recommend you to use this syntax for the Bearer:

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
Serge
  • 40,935
  • 4
  • 18
  • 45