Blazor Client应用程序配置请求将cookie发送在CORS上的cookie失败
我有一个大风WASM客户端应用程序,该应用程序试图在Localhost上向我的ASP.NET API发送cookie,但在不同的端口上,因此需要CORS。
我已经在API端配置并应用了CORS策略,但是我很难在客户端请求端找出正确的选项或标头设置。在Chrome Dev工具中,我在标题中看到了Cookie,但随着该侧面的Cookie的数量返回零,它似乎并没有达到API。
我已经直接使用浏览器进行了API控制器测试,并且Cookie的工作原理,因此CORS和Cookie一起必须是一个问题。
这是来自Glazor WASM客户端的操作中的代码段:(我已经评论了其他失败的配置尝试)
private async void CheckCookie()
{
HttpClient client = new HttpClient();
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost:7139/ValidateCookie");
//requestMessage.Options.Set(new HttpRequestOptionsKey<string>(),"true");
//requestMessage.Options.Append(new KeyValuePair<string, object>("credentials","include"));
requestMessage.Options.Set(new HttpRequestOptionsKey<string>("Access-Control-Request-Headers"),"Cookie");
requestMessage.Options.Set(new HttpRequestOptionsKey<string>("Access-Control-Allow-Origin"),"http://localhost:5196");
requestMessage.Options.Set(new HttpRequestOptionsKey<string>("Access-Control-Allow-Methods"),"GET");
//requestMessage.Headers.Add("Access-Control-Allow-Credentials","true");
//requestMessage.Headers.Add("withCredentials","true");
CommunityObject[] subbedCommunities;
List<CommunityObject> listSubbedCommunities = new List<CommunityObject>();
HttpResponseMessage returnMessage = await client.SendAsync(requestMessage);
var stream = returnMessage.Content.ReadAsStreamAsync();
var contentstring = returnMessage.Content.ReadAsStringAsync();
Console.WriteLine("Community CheckCookie return stream result: " + stream.Result);
cookieresult = contentstring.Result;
}
这是我当前的程序。CSCORS配置:(我还尝试过将Origins设置为Localhost:port-port-light-is-using)
builder.Services.AddCors(options =>
{
options.AddPolicy("CookiePolicy",
policy =>
{
policy.AllowCredentials().AllowAnyHeader().AllowAnyMethod().SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
});
以下是控制器:
public class ValidateCookieToken : ControllerBase
{
[EnableCors("CookiePolicy")]
[HttpGet("/ValidateCookie")]
public String Get()
{
String bearertoken;
Console.WriteLine("ValidateCookies Headers Keys: " + Request.Headers.Keys);
foreach (var VARIABLE in Request.Headers.Keys)
{
Console.WriteLine("ValCookie Key: " + VARIABLE + " - Value: " + Request.Headers[VARIABLE]);
}
Console.WriteLine("ValidateCookies current cookie count: " + Request.Cookies.Count);
Console.WriteLine("Validatecookies cookie keys: " + Request.Cookies.Keys);
Console.WriteLine("ValCook headers cookie: " + Request.Headers.Cookie.ToString());
Request.Cookies.TryGetValue("bearer", out bearertoken);
String decodedbearer = Encoding.ASCII.GetString(Convert.FromBase64String(bearertoken));
return decodedbearer;
}
}
在所有这些之上,是否可以记录CORS交易的方法,以便我可以从那以后进行一次调试。就目前而言,我不知道CORS Cookie的哪一侧,客户端或API被阻止。
编辑:下面是添加cookie的登录控制器。
[HttpGet("/Login")]
public String Get(String Email, String Pass)
{
String token = null;
token = Auth.Login(Email, Pass);
if (token != null)
{
String basicauth = Convert.ToBase64String(Encoding.ASCII.GetBytes(Email+":"+token));
CookieOptions cookieOptions = new CookieOptions();
Console.WriteLine("Cookie path is: " + cookieOptions.Path);
Console.WriteLine("Cookie domain is: " + cookieOptions.Domain);
Console.WriteLine("Cookie isEssential: " + cookieOptions.IsEssential);
Console.WriteLine("Cookie Samesite: " + cookieOptions.SameSite);
Console.WriteLine("Cookie secure: " + cookieOptions.Secure);
Console.WriteLine("Cookie expires: " + cookieOptions.Expires);
Console.WriteLine("Cookie httponly: " + cookieOptions.HttpOnly);
Console.WriteLine("Cookie max age: " + cookieOptions.MaxAge);
cookieOptions.IsEssential = true;
cookieOptions.SameSite = SameSiteMode.Lax;
cookieOptions.Secure = false;
Response.Cookies.Append("bearer",basicauth,cookieOptions);
Console.WriteLine("Cookie count after login: " + Request.Cookies.Count);
return basicauth;
}
return "token was null";
}
I have a Blazor WASM client app that is trying to send a cookie to my asp.net api, both on localhost but on different ports so CORS is required.
I've configured and applied a CORS policy on the API side but I'm having trouble figuring out the correct options or header setting on the client request side. In Chrome dev tools I see the cookie in the header but it doesn't seem to reach the API as the cookie count on that side returns zero.
I've tested the API controllers directly with GET in the browser and the cookie works so it must be an issue with CORS and cookies together.
This is a snippet of code from an action on the Blazor WASM client side: (I've commented out other failed configuration attempts)
private async void CheckCookie()
{
HttpClient client = new HttpClient();
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost:7139/ValidateCookie");
//requestMessage.Options.Set(new HttpRequestOptionsKey<string>(),"true");
//requestMessage.Options.Append(new KeyValuePair<string, object>("credentials","include"));
requestMessage.Options.Set(new HttpRequestOptionsKey<string>("Access-Control-Request-Headers"),"Cookie");
requestMessage.Options.Set(new HttpRequestOptionsKey<string>("Access-Control-Allow-Origin"),"http://localhost:5196");
requestMessage.Options.Set(new HttpRequestOptionsKey<string>("Access-Control-Allow-Methods"),"GET");
//requestMessage.Headers.Add("Access-Control-Allow-Credentials","true");
//requestMessage.Headers.Add("withCredentials","true");
CommunityObject[] subbedCommunities;
List<CommunityObject> listSubbedCommunities = new List<CommunityObject>();
HttpResponseMessage returnMessage = await client.SendAsync(requestMessage);
var stream = returnMessage.Content.ReadAsStreamAsync();
var contentstring = returnMessage.Content.ReadAsStringAsync();
Console.WriteLine("Community CheckCookie return stream result: " + stream.Result);
cookieresult = contentstring.Result;
}
Here is my current program.cs CORS configuration: (I've also tried with just setting the origins as the localhost:port-the-client-is-using)
builder.Services.AddCors(options =>
{
options.AddPolicy("CookiePolicy",
policy =>
{
policy.AllowCredentials().AllowAnyHeader().AllowAnyMethod().SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
});
Here is the controller being called:
public class ValidateCookieToken : ControllerBase
{
[EnableCors("CookiePolicy")]
[HttpGet("/ValidateCookie")]
public String Get()
{
String bearertoken;
Console.WriteLine("ValidateCookies Headers Keys: " + Request.Headers.Keys);
foreach (var VARIABLE in Request.Headers.Keys)
{
Console.WriteLine("ValCookie Key: " + VARIABLE + " - Value: " + Request.Headers[VARIABLE]);
}
Console.WriteLine("ValidateCookies current cookie count: " + Request.Cookies.Count);
Console.WriteLine("Validatecookies cookie keys: " + Request.Cookies.Keys);
Console.WriteLine("ValCook headers cookie: " + Request.Headers.Cookie.ToString());
Request.Cookies.TryGetValue("bearer", out bearertoken);
String decodedbearer = Encoding.ASCII.GetString(Convert.FromBase64String(bearertoken));
return decodedbearer;
}
}
On top of all of this, is there a way to log CORS transactions so I can atleast debug it from that end. As it stands I have no idea which side, client or API, the CORS cookie is getting blocked at.
Edit: Below is the login controller which adds the cookie.
[HttpGet("/Login")]
public String Get(String Email, String Pass)
{
String token = null;
token = Auth.Login(Email, Pass);
if (token != null)
{
String basicauth = Convert.ToBase64String(Encoding.ASCII.GetBytes(Email+":"+token));
CookieOptions cookieOptions = new CookieOptions();
Console.WriteLine("Cookie path is: " + cookieOptions.Path);
Console.WriteLine("Cookie domain is: " + cookieOptions.Domain);
Console.WriteLine("Cookie isEssential: " + cookieOptions.IsEssential);
Console.WriteLine("Cookie Samesite: " + cookieOptions.SameSite);
Console.WriteLine("Cookie secure: " + cookieOptions.Secure);
Console.WriteLine("Cookie expires: " + cookieOptions.Expires);
Console.WriteLine("Cookie httponly: " + cookieOptions.HttpOnly);
Console.WriteLine("Cookie max age: " + cookieOptions.MaxAge);
cookieOptions.IsEssential = true;
cookieOptions.SameSite = SameSiteMode.Lax;
cookieOptions.Secure = false;
Response.Cookies.Append("bearer",basicauth,cookieOptions);
Console.WriteLine("Cookie count after login: " + Request.Cookies.Count);
return basicauth;
}
return "token was null";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在客户端收到任何消息吗?您可能需要配置您的API不允许cookie标头或访问control-allow-credentials进行配置
跨越来源请求的设置cookie
https://livebook.manning.com/book/cors-in-行动/第5/4章
Do you get any message on the client side? It could be a preflight thing where your API doesn't allow cookie headers, or Access-Control-Allow-Credentials needs to be configured
Set cookies for cross origin requests
https://livebook.manning.com/book/cors-in-action/chapter-5/4