MVC 4联网的身份验证与自定义角色 [英] MVC 4 Intranet Authentication with Custom Roles

查看:161
本文介绍了MVC 4联网的身份验证与自定义角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了一些时间来搜索,发现了很多令人困惑的答案,所以我会张贴在这里澄清。

我使用MVC4 VS2012创建使用域身份验证的内部网站上。一切正常。但是,要管理即有机会获得这个web应用我preFER的不同区域不使用,我不能管理和也不能把Web应用程序的用户AD组的用户。

是否有其他选择吗?我认为这将涉及关联/存储属于自定义角色的域名,并使用授权属性来控制访问。

  [授权(角色=经理)]

任何人都可以建议最好的方式为这个或点我在正确的方向?

我看到一个类似的解决方案<一href=\"http://stackoverflow.com/questions/6043100/asp-net-mvc-and-windows-authentication-with-custom-roles\">link,但我仍然不知道如何使用这个对角色的存储列表,并验证对这些角色的用户。谁能细说如果此解决方案将工作?

 保护无效Application_AuthenticateRequest(对象发件人,EventArgs参数)
    {
        如果(HttpContext.Current!= NULL)
        {
            的String [] =角色GetRolesFromSomeDataTable(HttpContext.Current.User.Identity.Name);            主要的GenericPrincipal =新的GenericPrincipal(HttpContext.Current.User.Identity,角色);            = Thread.CurrentPrincipal中= HttpContext.Current.User本金;
        }
    }


解决方案

我使用的是SQL Server和这个配置MVC3。

Web.config文件:

 &LT;&的System.Web GT;
&LT; roleManager启用=真正的defaultProvider =SqlRoleManager&GT;
  &LT;供应商&GT;
    &LT;清/&GT;
    &LT;添加名称=SqlRoleManagerTYPE =System.Web.Security.SqlRoleProvider的connectionStringName =SqlRoleManagerConnection的applicationName =YourAppName/&GT;
  &LT; /供应商&GT;
&LT; / roleManager&GT;

...

 &LT;身份验证模式=窗口/&GT;

...

 &LT;&是connectionStrings GT;&LT;添加名称=SqlRoleManagerConnection的connectionString =数据源= YourDBServer;初始目录= AppServices;集成安全性= TRUE;的providerName = /&GT的OLE DB NET Framework数据提供。
&LT; /&是connectionStrings GT;

要inicialize角色:

的Global.asax.cs

 使用System.Web.Security;////
保护无效的Application_Start()
{   //你可以运行此code一次,然后在应用程序管理的其余部分。
   // 例如:   // Roles.CreateRole(管理员);
   // Roles.AddUserToRole(您的域\\\\管理用户,管理员);
   Roles.CreateRole(CustomRole);   Roles.AddUserToRole(您的域\\\\ DomainUser,CustomRole); }

在您的控制器

  [授权(角色=CustomRole)]
公共类HomeController的:控制器
 {

要管理用户

 公共类Usuario
{
    公共字符串用户名{获得;组; }
    公共字符串角色名{获得;组; }
    公共字符串名称{;组; }
    公共常量字符串域=您的域\\\\;
    公共无效删除()
    {
        Roles.RemoveUserFromRole(this.UserName,this.RoleName);
    }    公共无效保存()
    {
        如果(Roles.IsUserInRole(Usuario.Domain + this.UserName,this.RoleName)== FALSE)
        {
            Roles.AddUserToRole(Usuario.Domain + this.UserName,this.RoleName);
        }
    }
}

用户类

 公共类USUARIOS:列表&LT; Usuario&GT;
{    公共无效GetUsuarios()//获取应用程序的用户
    {        如果(Roles.RoleExists(CustomRole))
        {
            的foreach(在Roles.GetUsersInRole串_usuario(CustomRole))
            {
                VAR usuario =新Usuario();
                usuario.UserName = _usuario;
                usuario.RoleName =CustomRole;
                this.Add(usuario);
            }
        }
  //  公共无效GetUsuariosRed()//获取网络用户(AD)
    {
        VAR domainContext =新PrincipalContext(ContextType.Domain);
        VAR groupPrincipal = GroupPrincipal.FindByIdentity(domainContext,IdentityType.SamAccountName,域用户);        的foreach(在groupPrincipal.Members VAR项)
        {
            VAR usuario =新Usuario();
            usuario.UserName = item.SamAccountName;
            usuario.Name = item.Name;
            this.Add(usuario);
        }    }

您可以创建一个这样的管理控制器来管理用户:

  [授权(角色=AdminCustomRole)]
公共类AdminController:控制器
{//公众的ActionResult指数()
    {        VAR USUARIOS =新USUARIOS();
        Usuarios.GetUsuarios();
        返回查看(USUARIOS);    }[HTTPGET]
公众的ActionResult CREATEUSER()
    {        VAR USUARIOS =新USUARIOS();
        Usuarios.GetUsuariosRed();       返回查看(USUARIOS);    }//

在我的应用程序,自定义角色是固定的。

I have spent some time searching and found a lot of confusing answers, so I will post here for clarification.

I am using MVC4 VS2012 created an Intranet site using domain authentication. Everything works. However, to manage the users that have access to different areas of this webapp I prefer not to use AD groups that I cannot manage and nor can the users of the webapp.

Is there an alternative? I assume this would involve associating/storing domain names belonging to custom roles and using the Authorize attribute to control access.

[Authorize(Roles = "Managers")]

Can anyone suggest the best pattern for this or point me in the right direction?

I see a similar solution link, but I am still not sure how to use this against a stored list of roles and validate the user against those roles. Can anyone elaborate if this solution would work?

        protected void Application_AuthenticateRequest(object sender, EventArgs args)
    {
        if (HttpContext.Current != null)
        {
            String[] roles = GetRolesFromSomeDataTable(HttpContext.Current.User.Identity.Name);

            GenericPrincipal principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles);

            Thread.CurrentPrincipal = HttpContext.Current.User = principal;
        }
    }

解决方案

I'm using this configuration with SQL Server and MVC3.

Web.config:

<system.web>
<roleManager enabled="true" defaultProvider="SqlRoleManager">
  <providers>
    <clear />
    <add name="SqlRoleManager" type="System.Web.Security.SqlRoleProvider"   connectionStringName="SqlRoleManagerConnection" applicationName="YourAppName" />
  </providers>
</roleManager>

....

<authentication mode="Windows" />

....

<connectionStrings>

<add name="SqlRoleManagerConnection" connectionString="Data Source=YourDBServer;Initial Catalog=AppServices;Integrated Security=True;" providerName=".NET Framework Data Provider for OLE DB" />
</connectionStrings>

To inicialize roles:

Global.asax.cs

using System.Web.Security;

////
protected void Application_Start()
{

   //You could run this code one time and then manage the rest in your application.
   // For example:

   // Roles.CreateRole("Administrator");    
   // Roles.AddUserToRole("YourDomain\\AdminUser", "Administrator");


   Roles.CreateRole("CustomRole");   

   Roles.AddUserToRole("YourDomain\\DomainUser", "CustomRole");

 }

In your Controller

[Authorize(Roles ="CustomRole")]
public class HomeController : Controller
 {

To manage users

 public class Usuario
{
    public string UserName { get; set; }
    public string RoleName { get; set; }
    public string Name { get; set; }
    public const string Domain = "YourDomain\\";


    public void Delete()
    {
        Roles.RemoveUserFromRole(this.UserName, this.RoleName);
    }

    public void Save()
    {
        if (Roles.IsUserInRole(Usuario.Domain + this.UserName, this.RoleName) == false)
        {
            Roles.AddUserToRole(Usuario.Domain + this.UserName, this.RoleName);
        }
    }
}

Users Class

public class Usuarios : List<Usuario>
{

    public void GetUsuarios() //Get application's users
    {

        if (Roles.RoleExists("CustomRole"))
        {
            foreach (string _usuario in Roles.GetUsersInRole("CustomRole"))
            {
                var usuario = new Usuario();
                usuario.UserName = _usuario;
                usuario.RoleName = "CustomRole";
                this.Add(usuario);
            }
        }
  //

  public void GetUsuariosRed() //Get Network Users (AD)
    {
        var domainContext = new PrincipalContext(ContextType.Domain);
        var groupPrincipal = GroupPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, "Domain Users");

        foreach (var item in groupPrincipal.Members)
        {
            var usuario = new Usuario();
            usuario.UserName = item.SamAccountName;
            usuario.Name = item.Name;
            this.Add(usuario);
        }

    }

You can create an "Admin" controller like this, to manage the users:

[Authorize(Roles = "AdminCustomRole")]
public class AdminController : Controller
{

//

public ActionResult Index()
    {

        var Usuarios = new Usuarios();
        Usuarios.GetUsuarios();
        return View(Usuarios);

    }

[HttpGet]
public ActionResult CreateUser()
    {

        var Usuarios = new Usuarios();
        Usuarios.GetUsuariosRed();

       return View(Usuarios);

    }

//

In my application, custom roles are fixed.

这篇关于MVC 4联网的身份验证与自定义角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆