During the development of Device Manager, a bug has bothered me for a long time. Every time I tried to call the APIs in Device Portal through 127.0.0.1(local loopback) using HTTPS, it crashed with a 403 forbidden.
Why? It has never asked me for any server credentials so there's no reason for getting 403.
Reading a lot of documents, I finally figured out the reason why I get a 403.
In Microsoft's documents about Device Portal, referred that there is a CSRF Protection in order to protect against CSRF attacks. We need to add a header named 'X-CSRF-Token' which contains a unique token or else the request will be rejected. The content of this additional header, according to the document, is delivered from a session cookie. It means we need to set up a connection first to get the cookie. Then add the 'X-CSRF-Token' header and copy the cookie's value to the header.
Like that:
var res=await client.GetAsync(new Uri($"https://{Address}/default.htm"));
if(filter!=null)
{
var cookies = filter.CookieManager.GetCookies(new Uri($"https://{Address}/default.htm")).Where(x=>x.Name== "CSRF-Token");
foreach(var i in cookies)
{
client.DefaultRequestHeaders.Add("X-CSRF-Token", i.Value);
}
}
Then everything will be fine, though I still don't know why Microsoft added this protection and why the darn HTTP connection don't work on local loopbacks.