单个网站中的多个ASP.NET身份验证

时间:2016-02-03 19:27:18

标签: asp.net-mvc-4 authentication asp.net-identity identity

我目前正在构建一个新的ASP.NET MVC 5项目,其中包含专用于管理员的专用部分。 本节以模块化方式开发,并具有自己的身份验证(使用ASP.NET标识) 我还想为同一网站中具有不同身份验证的客户提供受限制的部分(使用ASP.NET身份)。

是否可以根据网站的位置设置不同的User.Identity对象? (例如:网站根目录中的“ClientUser”和“外联网”中的“ExtranetUser”)

以下是我目前对这两个部分的代码:

客户端部分(主ASP.NET应用程序):

public void ConfigureAuth(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                CookieName = "ClientCookie",
                LoginPath = new PathString("/Account/LoginRegister"),
                ExpireTimeSpan = TimeSpan.FromHours(4),
                Provider = new CookieAuthenticationProvider()
            });
        }

外联网部分(存储在模块项目中):

public void ConfigureAuth(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                CookieName = "ExtranetCookie",
                LoginPath = new PathString("/Extranet/Account/Login"),
                Provider = new CookieAuthenticationProvider()
            });
        }

谢谢!

1 个答案:

答案 0 :(得分:0)

当然,您的应用程序中可以包含多个DbContext(或IdentityDbContext)个元素。问题是在启动期间,您需要提供从CreatePerOwinContext开始的数据库和UserManager。事件可以按this post

中所示进行处理

定义您的两个User和SignIn管理器类:

public void ConfigureAuth(IAppBuilder app)
{
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

    // Add our custom managers
    app.CreatePerOwinContext<CustomUserManager>(CustomUserManager.Create);
    app.CreatePerOwinContext<CustomSignInManager>(CustomSignInManager.Create);
}

并在相应的控制器中引用正确的实现:

private CustomSignInManager _signInManager;
public CustomSignInManager CustomSignInManager
{
    get
    {
        return _signInManager ?? HttpContext.GetOwinContext().Get<CustomSignInManager>();
    }
    private set { _signInManager = value; }
}

我没有亲自尝试,但approch看起来很聪明。

相关问题