【发布时间】:2017-09-10 15:39:08
【问题描述】:
我正在使用 Cookie 中间件对用户进行身份验证。我一直在关注this official tutorial。
在我的Startup 类中,我的Configure 方法的摘录如下所示:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// ...
// Cookie-based Authentication
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme,
AutomaticAuthenticate = true,
AutomaticChallenge = true,
Events = new CustomCookieAuthenticationEvents(app),
});
// ...
}
CustomCookieAuthenticationEvents 类定义如下:
public class CustomCookieAuthenticationEvents : CookieAuthenticationEvents
{
private IApplicationBuilder _app;
private IMyService _myService = null;
private IMyService MyService
{
get
{
if(_myService != null)
{
return _myService;
} else
{
return _myService = (IMyService) _app.ApplicationServices.GetService(typeof(IMyService));
}
}
}
public CustomCookieAuthenticationEvents(IApplicationBuilder app)
{
_app = app;
}
public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
{
string sessionToken = context.Principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Sid)?.Value;
LogonSession response = null;
var response = await MyService.CheckSession(sessionToken);
if (response == null)
{
context.RejectPrincipal();
await context.HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
}
}
由于 Startup.Configure 不提供依赖注入(当时甚至没有注册服务),我做了一些解决方法:
- 将 IApplicationBuilder 服务传递给
CustomCookieAuthenticationEvents类 - 在第一次请求时在只读属性中获取
IMyService(单例模式)
tl;博士
我的解决方案有效,但它丑陋。不涉及依赖注入,因为当时不可能。
问题的本质是我必须实例化CustomCookieAuthenticationEvents。据我阅读source code,没有办法解决这个问题,因为如果我省略options 参数,UseCookieAuthentication 会抛出异常。
有什么建议可以让我目前的解决方案更好?
【问题讨论】:
-
Service.Configure是什么? -
这是一个错字。我的意思是
Startup.Configure。
标签: asp.net dependency-injection configuration asp.net-core startup