注入SignInManager依赖项:不能与Unity一起使用,在使用OWIN时有效

 个信2602926933 发布于 2022-12-11 10:50

我正在向ASP.NET MVC 5 Web应用程序添加ASP.NET身份验证功能.

我在整个项目中使用Unity进行依赖注入,所以我决定注入AccountController构造函数中所需的依赖项:

public AccountController(UserManager userManager, SignInManager signInManager)
{
    _userManager = userManager;
    _signInManager = signInManager;
}

我的Login方法实现如下(实际上,我从ASP.NET Web Application具有Individual User Accounts身份验证的项目模板中复制了该代码):

//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task Login(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!
}

问题是,认证工作不正常-即使我进入了正确的凭据,resultSignInStatus.Success有在响应不发送身份验证cookie.

但是,如果我使用OWIN基础结构来解析ApplicationSignInManager而不是Unity容器,一切都正常:

//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task Login(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 ApplicationSignInManagerCreate方法提供了与构造函数相同的依赖关系.但Unity的方法由于某种原因不起作用:成功登录后不会发送身份验证cookie.

这是一个非常具体的问题,但也许有人之前遇到过这样的问题?我相信这种行为应该与OWIN中间件,管道以及在应用程序启动时如何连接所有这些东西有关.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有