【问题标题】:ASP.NET Core session authenticationASP.NET Core 会话身份验证
【发布时间】:2020-01-19 12:37:55
【问题描述】:

我正在开发一个 ASP.NET Core 2.2 Web 应用程序。我想将用户声明存储在应用程序内存中,而不是 cookie 中。

我按照here 的描述添加了AddDistributedMemoryCacheAddSessionUseSession,但是当请求页面时,我仍然看到发送到服务器并从服务器接收到的cookie 数据。

我的Startup 班级:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromSeconds(10);
            options.Cookie.HttpOnly = true;
            // Make the session cookie essential
            options.Cookie.IsEssential = true;
        });

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>()
            .AddDefaultUI(UIFramework.Bootstrap4)
            .AddEntityFrameworkStores<ApplicationDbContext>();


        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSession();
        app.UseCookiePolicy();

        app.UseAuthentication();

        app.UseMvc();
    }
}

Cookie 数据:

cookie: .AspNet.Consent=yes; .aspnetcore.antiforgery.wgd7b_ovteu = cfdj8k-fe5fucclfpiyhglvwwky0rplnazqx6jnn1muqjdbx0uk4c310gp8l2rhdwlshmoyjihqxxguub5gng742rl7n-ugtynsnz09jsb11kvgrcxagqk5yaznbcaqgq0tijucokadwxegykc2fc3-vvcy; .AspNetCore.Identity.Application = CfDJ8K-fe5FucclFpIYHgLvWwKaod7oR4502P-cppU0aQI_WYHsvaTEL-Y5Ca1hnJOBznUpadpPkq5ubrH04UhMBpXTnK1ASjuMXMPBhr3PKqPSnXPYPFmhgki1_RicCVDQyl7mRYuWPUY2RjVkgoEIXCBj96zCRK9PWZo0N6N4hAETl-z0LAExj1Sjo6Xz3uWvHsg5GtJijlQmE6BjSh0ObMulxgDFJZEw13IbWJmlLFv7kdvs9va59wBPlEhHFER1Rs0iKW2cpVqQTPK7SjgQrSlo8_KQYHWzYa3xFSjuhrWJnm-Y4u9jXA6yCoaVxG1U-1EbOaQRfUXFs2F9IX6dU7iExsNqhPR4o2CKlt6ERI0JT_p7jHv0hrHbBiUjUVMYi_qoAQRv1OXfVZBLkoRve20gvjQtD3aRZFZR5poX-bq0pw6CNBTLexzD_bU1jJnpaf61OKbQM2-qJnWPS7YayFjJt3k_qALbnquUsSBMDMm3PoFcU26_Ubyu6RTZ-aanKc1bdcEA5o3WF8JksZkrvRFhZZuvWahDpnQCxxy-rELKwXcybcWHi-QB7gxSm6Q6S84NX2390mbHVJ1RO8eUmUF4 P>

我怎样才能让它只存储在内存中,而不是 cookie 中?

【问题讨论】:

    标签: c# authentication asp.net-core cookies session-cookies


    【解决方案1】:

    身份cookie认证需要设置SessionStore,所以你的认证cookie只是一个标识符。

    代替

    services.AddDefaultIdentity<IdentityUser>()
    

    使用这个

    services.AddAuthentication(o =>
    {
        o.DefaultScheme = IdentityConstants.ApplicationScheme;
        o.DefaultSignInScheme = IdentityConstants.ExternalScheme;
    }).AddIdentityCookies(o =>
    {
        o.ApplicationCookie.PostConfigure(cookie => cookie.SessionStore = new MemoryCacheTicketStore());
    });
    
    services.AddIdentityCore<IdentityUser>(o =>
    {
        o.Stores.MaxLengthForKeys = 128;
    }).AddDefaultUI()
    .AddDefaultTokenProviders();
    

    MemoryCacheTicketStore.cs

    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);
        }
    }
    

    【讨论】:

    • 我收到错误“InvalidOperationException:无法解析类型“Microsoft.AspNetCore.Identity.IUserStore1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager1[Microsoft.AspNetCore.Identity.IdentityUser]”的服务。”
    • 您是否也删除了 AddEntityFrameworkStore ?如果是这样,把他们带回来
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 2021-03-28
    • 2017-03-30
    • 2018-06-25
    • 2016-05-19
    • 2018-05-13
    • 2017-05-17
    相关资源
    最近更新 更多