asp.net-core - Xamarin.Forms Cookie/用户持久性和 ASP.NET Core 身份验证/Cookie
问题描述
希望我不会误解有关 ASP.NET 身份验证的一些基本知识,但这是我想要完成的事情(并且没有这样做):
我有一个 Xamarin.Forms 应用程序,它需要能够处理 ASP.NET Web 服务。当我运行应用程序本身时,它工作正常。它的 ASP.NET 端使用 Cookie 身份验证,并且应用程序能够从 Cookie 容器中获取 Cookie——然后将其序列化/存储到安全存储中:
例如:
var baseUri = new Uri(url);
baseUri = new Uri($"{baseUri.Scheme}://{baseUri.Host}");
var cookieContainer = new CookieContainer();
/*
authenticationCookie is stored locally and de/serialized via Json from SecureStorage:
var cookie = SecureStorage.GetAsync(AuthenticationCookieKey).Result;
if (!string.IsNullOrEmpty(cookie))
{
authenticationCookie = JsonConvert.DeserializeObject<Cookie>(cookie);
}
*/
cookieContainer.Add(authenticationCookie);
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
{
using (var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(content) })
{
using (var client = new HttpClient(handler))
{
return client.SendAsync(request).Result;
}
}
}
当我登录时,我对“成功”执行以下操作:
SetAuthenticationCookie(cookieContainer.GetCookies(baseUri)[0]);
这会在类中设置本地“authenticationCookie”,然后将其序列化到 SecureStorage。
我已经证明/检查了 authenticationCookie 是否正确反序列化并在 Xamarin.Forms 应用程序执行时加载。我已将其附加到我的网络请求中。但是,当我拨打电话时,我从 ASP.NET Core 的另一端收到了一个登录请求。
ASP.NET Core 服务器本身工作正常。如果我有一个浏览器实例,它永远不会要求我登录并且浏览器“记住”并正确应用登录中的 cookie。但是,Xamarin.Forms 应用程序似乎没有。
我错过了什么?
为了争论,这就是我通过 Login 方法设置 cookie 的方式:
//user has a User loaded from EF at this point
var userPrincipal = new ClaimsPrincipal(
new ClaimsIdentity(
new List<Claim>()
{
new Claim(ClaimTypes.Name, user.EmailAddress)
}, "Login"));
var properties = new AuthenticationProperties()
{
IsPersistent = true
};
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, properties);
解决方案
因此,我成功地在所选答案下使用了答案:
如何在 HttpClient 的 HttpRequestMessage 上设置 cookie
显然设置了 CookieContainer,然后用 Cookie 填充它,并将其包含在 Message DID NOT WORK 中。
解决方案是手动添加 Cookie,执行以下操作:
private HttpResponseMessage GetDataResponse(string url)
{
using (var handler = new HttpClientHandler { UseCookies = false })
{
using (var request = new HttpRequestMessage(HttpMethod.Get, url))
{
request.Headers.Add("Cookie", $"{MyCookie.Name}={MyCookie.Value}");
using (var client = new HttpClient(handler))
{
return client.SendAsync(request).Result;
}
}
}
}
这完全符合我们的预期!
推荐阅读
- java - 如何从 Java 中的应用程序内部检查 grpc 服务器的就绪情况
- bash - 将参数传递给作为不同脚本的参数的脚本
- r - 根据重叠模式删除部分字符串
- c# - C#:如何解决安装项目中的文本框错误?
- node.js - 我们如何为 jenkins 进行 rsa 密钥交换,为 scp(ec2) 进行远程服务器?
- hadoop - Phoenix -> csv -> 封装令牌和分隔符之间的无效字符
- java - 将 Java 通用 Lambda 参数传递给方法本地调用
- javascript - 从反应选择中清除值
- single-sign-on - 我如何为 ios 13 实现单点登录扩展
- json - Kusto KQL 引用 JSON 数组中的第一个对象