.NET Core 2.2 Cookie身份验证无法记住用户

时间:2019-04-08 10:06:02

标签: .net authentication web cookies core

大家好,我遇到了Cookie身份验证问题。当我运行该应用程序并使用以下代码登录用户时,一切正常,但是当我关闭我的项目(添加一些代码等)并再次运行时,我必须再次登录。我使用cookie身份验证,我认为系统应该记住该cookie,并在项目关闭后让我保持登录状态。我错了吗?

我使用asp.core 2.2

                await HttpContext.SignInAsync(
                        CookieAuthenticationDefaults.AuthenticationScheme,
                        principal, new AuthenticationProperties()
                        {
                            AllowRefresh = true,
                            IsPersistent = true,
                            ExpiresUtc = DateTime.UtcNow.AddDays(7)
                        });

这是我在Startup类中设置它的方式

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie(options =>
            {
                options.LoginPath = new PathString("/Account/LogOn");
                options.LogoutPath = new PathString("/Account/LogOut");
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                options.SessionStore = new MemoryCacheTicketStore();
            });

也许是因为这个MemoryCacheTickerStore类?我必须实现它,因为在唱歌后如果没有它,我会遇到一个错误,该请求太长并添加了此错误。

public class MemoryCacheTicketStore : ITicketStore
{
    private const string KeyPrefix = "AuthSessionStore-";
    private IMemoryCache _cache;

    public MemoryCacheTicketStore()
    {
        _cache = new MemoryCache(new MemoryCacheOptions());
    }

    public async Task<string> StoreAsync(AuthenticationTicket ticket)
    {
        var guid = Guid.NewGuid();
        var key = KeyPrefix + guid.ToString();
        await RenewAsync(key, ticket);
        return key;
    }

    public Task RenewAsync(string key, AuthenticationTicket ticket)
    {
        var options = new MemoryCacheEntryOptions();
        var expiresUtc = ticket.Properties.ExpiresUtc;
        if (expiresUtc.HasValue)
        {
            options.SetAbsoluteExpiration(expiresUtc.Value);
        }
        options.SetSlidingExpiration(TimeSpan.FromHours(1)); // TODO: configurable.

        _cache.Set(key, ticket, options);

        return Task.FromResult(0);
    }

    public Task<AuthenticationTicket> RetrieveAsync(string key)
    {
        AuthenticationTicket ticket;
        _cache.TryGetValue(key, out ticket);
        return Task.FromResult(ticket);
    }

    public Task RemoveAsync(string key)
    {
        _cache.Remove(key);
        return Task.FromResult(0);
    }
}

0 个答案:

没有答案