首页 > 解决方案 > 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);

标签: asp.net-corexamarin.forms

解决方案


因此,我成功地在所选答案下使用了答案:

如何在 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;
                }
            }
        }
    }

这完全符合我们的预期!


推荐阅读