[英]Blazor Client App configuring request to send cookies on CORS failing
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.我有一个 Blazor WASM 客户端应用程序试图将 cookie 发送到我的 asp.net api,都在本地主机上但在不同的端口上,因此需要 CORS。
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.我已经在 API 端配置并应用了 CORS 策略,但在客户端请求端找出正确的选项或标头设置时遇到问题。 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.在 Chrome 开发工具中,我在标题中看到了 cookie,但它似乎没有到达 API,因为那一侧的 cookie 计数返回零。
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.我已经在浏览器中直接使用 GET 测试了 API 控制器,并且 cookie 可以正常工作,所以它一定是 CORS 和 cookie 一起出现的问题。
This is a snippet of code from an action on the Blazor WASM client side: (I've commented out other failed configuration attempts)这是来自 Blazor 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;
}
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)这是我当前的 program.cs CORS 配置:(我也尝试将源设置为 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.最重要的是,有没有办法记录 CORS 事务,所以我至少可以从那一端调试它。 As it stands I have no idea which side, client or API, the CORS cookie is getting blocked at.就目前而言,我不知道 CORS cookie 在哪一方、客户端或 API 被阻止。
Edit: Below is the login controller which adds the cookie.编辑:下面是添加 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";
}
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这可能是您的 API 不允许 cookie 标头或需要配置 Access-Control-Allow-Credentials 的预检事项
Set cookies for cross origin requests 为跨源请求设置 cookie
https://livebook.manning.com/book/cors-in-action/chapter-5/4https://livebook.manning.com/book/cors-in-action/chapter-5/4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.