c# - ASP.NET Core 会话身份验证
问题描述
我正在开发一个 ASP.NET Core 2.2 Web 应用程序。我想将用户声明存储在应用程序内存中,而不是 cookie 中。
我添加了AddDistributedMemoryCache
,AddSession
和UseSession
描述的here,但是当页面被请求时,我仍然看到发送到服务器并从服务器接收到的 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:.AspNet.Consent=yes;.AspNetCore.Antiforgery.WGD7B_OvtEU=CfDJ8K-fe5FucclFpIYHgLvWwKY0RPLnAZQX6JnN1muQjDbx0UK4C310gp8L2RHdWlsHmoYJihQxtGuUB5GNG742rl7N-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
我怎样才能让它只存储在内存中,而不是 cookie 中?
解决方案
身份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);
}
}
推荐阅读
- xamarin - Xamarin froms Forms 水平列表视图,带有将日期向右、向左移动的按钮
- arrays - 如何根据参数对对象列表进行分类
- github - 如何更改 GitHub 拉取请求中使用的作者/用户名?
- wix - MSI 失败时,WiX 引导程序显示错误
- java - 插入场景中按版本的 JPA/Hibernate 乐观锁
- laravel - Laravel,显示 dd() 结果而不用 die -> d(),dump()?
- angular - 错误 TS2339:“订阅”类型上不存在属性“订阅”
- javascript - 自定义组件不是 Angular CLI 应用程序中的已知元素
- python - 使用 Python 将 np.array 保存到 netCDF4 文件
- node.js - 使用 webdriverio 测试本机应用程序时发送 HTTP POST