我有一个.NET Core 3项目(最近从2.2升级而来(,它使用Redis分布式缓存和cookie身份验证。
目前看起来是这样的:
public void ConfigureServices(IServiceCollection services)
{
// Set up Redis distributed cache
services.AddStackExchangeRedisCache(...);
...
services.ConfigureApplicationCookie(options =>
{
...
// Get a service provider to get the distributed cache set up above
var cache = services.BuildServiceProvider().GetService<IDistributedCache>();
options.SessionStore = new MyCustomStore(cache, ...);
}):
}
问题是BuildServiceProvider()
导致生成错误:
Startup.cs(…(:警告ASP0000:从应用程序代码调用"BuildServiceProvider"会导致创建一个附加的单例服务副本。考虑将依赖注入服务等替代方案作为"配置"的参数。
这似乎不是一个选项-ConfigureApplicationCookie
在Startup.ConfigureServices
中,只能配置新服务,Startup.Configure
可以使用新服务,但不能将CookieAuthenticationOptions.SessionStore
覆盖为我的自定义存储。
我尝试在ConfigureApplicationCookie
之前添加services.AddSingleton<ITicketStore>(p => new MyCustomRedisStore(cache, ...))
,但这被忽略了。
显式设置CookieAuthenticationOptions.SessionStore
似乎是唯一的方法,可以让它使用本地内存存储以外的任何东西。
我在网上找到的每个示例都使用BuildServiceProvider()
;
理想情况下,我想做一些类似的事情:
services.ConfigureApplicationCookieStore(provider =>
{
var cache = provider.GetService<IDistributedCache>();
return new MyCustomStore(cache, ...);
});
或
public void Configure(IApplicationBuilder app, ... IDistributedCache cache)
{
app.UseApplicationCookieStore(new MyCustomStore(cache, ...));
}
然后CookieAuthenticationOptions.SessionStore
应该只使用我在那里配置的任何东西。
如何使应用程序cookie使用注入的存储
参考使用DI服务配置选项
如果您的自定义存储的所有依赖项都是可注入的,那么只需向服务集合注册您的存储和所需的依赖项,并使用DI服务来配置选项
public void ConfigureServices(IServiceCollection services) {
// Set up Redis distributed cache
services.AddStackExchangeRedisCache(...);
//register my custom store
services.AddSingleton<ITicketStore, MyCustomRedisStore>();
//...
//Use DI services to configure options
services.AddOptions<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme)
.Configure<ITicketStore>((options, store) => {
options.SessionStore = store;
});
services.ConfigureApplicationCookie(options => {
//do nothing
}):
}
如果没有,则围绕实际注册的进行工作
例如
//Use DI services to configure options
services.AddOptions<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme)
.Configure<IDistributedCache>((options, cache) => {
options.SessionStore = new MyCustomRedisStore(cache, ...);
});
注:
ConfigureApplicationCookie
使用命名的选项实例。-@柯克拉金
public static IServiceCollection ConfigureApplicationCookie(this IServiceCollection services, Action<CookieAuthenticationOptions> configure)
=> services.Configure(IdentityConstants.ApplicationScheme, configure);
在将该选项添加到服务时,该选项需要包含该名称。
为了在.NET Core 3.0中实现Redis Tickets,我们做了以下操作,这是上面的最终形式::
services.AddSingleton<ITicketStore, RedisTicketStore>();
services.AddOptions<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme)
.Configure<ITicketStore>((options, store) => {
options.SessionStore = store;
});
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
// ...configure identity server options
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme);
以下是Redis的实现:
public class RedisTicketStore : ITicketStore
{
private const string KeyPrefix = "AuthSessionStore-";
private IDistributedCache cache;
public RedisTicketStore(IDistributedCache cache)
{
this.cache = cache;
}
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 DistributedCacheEntryOptions();
var expiresUtc = ticket.Properties.ExpiresUtc;
if (expiresUtc.HasValue)
{
options.SetAbsoluteExpiration(expiresUtc.Value);
}
byte[] val = SerializeToBytes(ticket);
cache.Set(key, val, options);
return Task.FromResult(0);
}
public Task<AuthenticationTicket> RetrieveAsync(string key)
{
AuthenticationTicket ticket;
byte[] bytes = null;
bytes = cache.Get(key);
ticket = DeserializeFromBytes(bytes);
return Task.FromResult(ticket);
}
public Task RemoveAsync(string key)
{
cache.Remove(key);
return Task.FromResult(0);
}
private static byte[] SerializeToBytes(AuthenticationTicket source)
{
return TicketSerializer.Default.Serialize(source);
}
private static AuthenticationTicket DeserializeFromBytes(byte[] source)
{
return source == null ? null : TicketSerializer.Default.Deserialize(source);
}
}
Redis实现来自:https://mikerussellnz.github.io/.NET-Core-Auth-Ticket-Redis/