我正在向ASP.NET MVC 5 Web应用程序添加ASP.NET身份验证功能.
我在整个项目中使用Unity进行依赖注入,所以我决定注入AccountController
构造函数中所需的依赖项:
public AccountController(UserManageruserManager, SignInManager signInManager) { _userManager = userManager; _signInManager = signInManager; }
我的Login
方法实现如下(实际上,我从ASP.NET Web Application
具有Individual User Accounts
身份验证的项目模板中复制了该代码):
// // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async TaskLogin(LoginViewModel model, string returnUrl) { var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: true); // Process result and return appropriate view... // However, there are no authentication cookies in the response! }
问题是,认证工作不正常-即使我进入了正确的凭据,result
是SignInStatus.Success
有在响应不发送身份验证cookie.
但是,如果我使用OWIN
基础结构来解析ApplicationSignInManager
而不是Unity容器,一切都正常:
// // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async TaskLogin(LoginViewModel model, string returnUrl) { var owinSignInManager = HttpContext.GetOwinContext().Get (); var result = await owinSignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: true); // Process result and return appropriate view... // Authentication cookies are present in the response! }
这ApplicationSignInManager
就是在应用程序Startup
类中注册的方式:
app.CreatePerOwinContext(ApplicationSignInManager.Create);
这是ApplicationSignInManager
声明:
public class ApplicationSignInManager : SignInManager{ public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) : base(userManager, authenticationManager) { } public static ApplicationSignInManager Create(IdentityFactoryOptions options, IOwinContext context) { var userManager = new ApplicationUserManager(new UserStore (new DatabaseContext())); return new ApplicationSignInManager(userManager, context.Authentication); } }
这是我的Unity配置的一部分:
unityContainer.RegisterType(new InjectionFactory(c => new HttpContextWrapper(HttpContext.Current))); unityContainer.RegisterType (new InjectionFactory(c => c.Resolve ().GetOwinContext())); unityContainer.RegisterType (new InjectionFactory(c => c.Resolve ().Authentication));
这个想法是Unity ApplicationSignInManager
为Create
方法提供了与构造函数相同的依赖关系.但Unity的方法由于某种原因不起作用:成功登录后不会发送身份验证cookie.
这是一个非常具体的问题,但也许有人之前遇到过这样的问题?我相信这种行为应该与OWIN中间件,管道以及在应用程序启动时如何连接所有这些东西有关.