36

私はコントローラーを持っていて、2つの役割がそれにアクセスできるようにしたいです。1-管理者または2-モデレーター

[Authorize(Roles = "admin、moderators")]を実行できることは知っていますが、列挙型で自分の役割を担っています。列挙型では、1つの役割しか許可できません。2つを承認する方法がわかりません。

[Authorize(Roles = MyEnum.Admin、MyEnum.Moderator)]のようなものを試しましたが、コンパイルされません。

誰かがかつてこれを提案しました:

 [Authorize(Roles=MyEnum.Admin)]
 [Authorize(MyEnum.Moderator)]
 public ActionResult myAction()
 {
 }

ただし、ORとしては機能しません。この場合、ユーザーは両方の役割の一部である必要があると思います。構文を見落としていますか?それとも、これは私が自分のカスタム認証をロールする必要がある場合ですか?

4

7 に答える 7

42

これは、次の構文を簡単に使用できるシンプルでエレガントなソリューションです。

[AuthorizeRoles(MyEnum.Admin, MyEnum.Moderator)]

独自の属性を作成するときparamsは、コンストラクターでキーワードを使用します。

public class AuthorizeRoles : AuthorizeAttribute
{
    public AuthorizeRoles(params MyEnum[] roles)
    {
        ...
    }
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        ...
    }
}

これにより、次のように属性を使用できるようになります。

[AuthorizeRoles(MyEnum.Admin, MyEnum.Moderator)]
public ActionResult myAction()
{
}
于 2012-01-05T15:20:51.493 に答える
32

次のようにビットOR演算子を使用してみてください。

[Authorize(Roles= MyEnum.Admin | MyEnum.Moderator)]
public ActionResult myAction()
{
}

それがうまくいかない場合は、自分でロールすることができます。私は現在、自分のプロジェクトでこれを行っています。これが私がしたことです:

public class AuthWhereRole : AuthorizeAttribute
{
    /// <summary>
    /// Add the allowed roles to this property.
    /// </summary>
    public UserRole Is;

    /// <summary>
    /// Checks to see if the user is authenticated and has the
    /// correct role to access a particular view.
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException("httpContext");

        // Make sure the user is authenticated.
        if (!httpContext.User.Identity.IsAuthenticated)
            return false;

        UserRole role = someUser.Role; // Load the user's role here

        // Perform a bitwise operation to see if the user's role
        // is in the passed in role values.
        if (Is != 0 && ((Is & role) != role))
            return false;

        return true;
    }
}

// Example Use
[AuthWhereRole(Is=MyEnum.Admin|MyEnum.Newbie)]
public ActionResult Test() {}

また、列挙型にフラグ属性を追加し、それらがすべて1以上の値であることを確認してください。このような:

[Flags]
public enum Roles
{
    Admin = 1,
    Moderator = 1 << 1,
    Newbie = 1 << 2
    etc...
}

左ビットシフトは、値1、2、4、8、16などを提供します。

まあ、これが少し役立つことを願っています。

于 2009-07-18T19:33:22.197 に答える
12

ここでいくつかのソリューションを組み合わせて、個人的なお気に入りを作成しました。私のカスタム属性は、SimpleMembershipが期待する形式にデータを変更し、他のすべてを処理できるようにします。

私の役割の列挙:

public enum MyRoles
{
    Admin,
    User,
}

ロールを作成するには:

public static void CreateDefaultRoles()
{
    foreach (var role in Enum.GetNames(typeof(MyRoles)))
    {
       if (!Roles.RoleExists(role))
       {
            Roles.CreateRole(role);
        }
    }
}

カスタム属性:

public class AuthorizeRolesAttribute : AuthorizeAttribute
{
    public AuthorizeRolesAttribute(params MyRoles[] allowedRoles)
    {
        var allowedRolesAsStrings = allowedRoles.Select(x => Enum.GetName(typeof(MyRoles), x));
        Roles = string.Join(",", allowedRolesAsStrings);
    }
}

そのように使用されます:

[AuthorizeRoles(MyRoles.Admin, MyRoles.User)]
public ActionResult MyAction()
{
    return View();
}
于 2013-02-11T18:21:49.253 に答える
2

試す

public class CustomAuthorize : AuthorizeAttribute
{
    public enum Role
    {
        DomainName_My_Group_Name,
        DomainName_My_Other_Group_Name
    }

    public CustomAuthorize(params Role[] DomainRoles)
    {
        foreach (var domainRole in DomainRoles)
        {
            var domain = domainRole.ToString().Split('_')[0] + "_";
            var role = domainRole.ToString().Replace(domain, "").Replace("_", " ");
            domain=domain.Replace("_", "\\");
            Roles += ", " + domain + role;
        }
        Roles = Roles.Substring(2);
    }       
}

public class HomeController : Controller
{
    [CustomAuthorize(Role.DomainName_My_Group_Name, Role.DomainName_My_Other_Group_Name)]
    public ActionResult Index()
    {
        return View();
    }
}
于 2012-05-04T09:06:25.870 に答える
1

これが私のバージョンで、@CalebHCと@LeeHaroldの回答に基づいています。

属性で名前付きパラメーターを使用するスタイルに従い、基本クラスのRolesプロパティをオーバーライドしました。

@CalebHCの回答では、Is不要と思われる新しいプロパティを使用しています。これAuthorizeCore()は、オーバーライドされているため(基本クラスではロールを使用しているため)、独自のプロパティも使用するのが理にかなってRolesいます。独自の属性を使用することで、他の.Net属性のスタイルに従うコントローラーRolesに書き込むことができます。Roles = Roles.Admin

2つのコンストラクターを使用CustomAuthorizeAttributeして、渡される実際のActive Directoryグループ名を表示しました。本番環境では、パラメーター化されたコンストラクターを使用して、クラス内のマジックストリングを回避します。グループ名は、作成中にweb.configから取得されApplication_Start()、DIを使用して作成時に渡されます。道具。

フォルダNotAuthorized.cshtmlにまたは同様のものが必要です。そうしないと、許可されていないユーザーにエラー画面が表示されます。Views\Shared

基本クラスAuthorizationAttribute.csのコードは次のとおりです。

コントローラ:

public ActionResult Index()
{
  return this.View();
}

[CustomAuthorize(Roles = Roles.Admin)]
public ActionResult About()
{
  return this.View();
}

CustomAuthorizeAttribute:

// The left bit shifting gives the values 1, 2, 4, 8, 16 and so on.
[Flags]
public enum Roles
{
  Admin = 1,
  User = 1 << 1    
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
  private readonly string adminGroupName;

  private readonly string userGroupName;

  public CustomAuthorizeAttribute() : this("Domain Admins", "Domain Users")
  {      
  }

  private CustomAuthorizeAttribute(string adminGroupName, string userGroupName)
  {
    this.adminGroupName = adminGroupName;
    this.userGroupName = userGroupName;
  }

  /// <summary>
  /// Gets or sets the allowed roles.
  /// </summary>
  public new Roles Roles { get; set; }

  /// <summary>
  /// Checks to see if the user is authenticated and has the
  /// correct role to access a particular view.
  /// </summary>
  /// <param name="httpContext">The HTTP context.</param>
  /// <returns>[True] if the user is authenticated and has the correct role</returns>
  /// <remarks>
  /// This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.
  /// </remarks>
  protected override bool AuthorizeCore(HttpContextBase httpContext)
  {
    if (httpContext == null)
    {
      throw new ArgumentNullException("httpContext");
    }

    if (!httpContext.User.Identity.IsAuthenticated)
    {
      return false;
    }

    var usersRoles = this.GetUsersRoles(httpContext.User);

    return this.Roles == 0 || usersRoles.Any(role => (this.Roles & role) == role);
  }

  protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
  {
    if (filterContext == null)
    {
      throw new ArgumentNullException("filterContext");
    }

    filterContext.Result = new ViewResult { ViewName = "NotAuthorized" };
  }

  private IEnumerable<Roles> GetUsersRoles(IPrincipal principal)
  {
    var roles = new List<Roles>();

    if (principal.IsInRole(this.adminGroupName))
    {
      roles.Add(Roles.Admin);
    }

    if (principal.IsInRole(this.userGroupName))
    {
      roles.Add(Roles.User);
    }

    return roles;
  }    
}
于 2012-10-17T23:20:53.160 に答える
0

CalebHCのコードに追加し、複数の役割を持つユーザーの処理に関するssmithの質問に答えるには...

カスタムセキュリティプリンシパルは、ユーザーが属するすべてのグループ/ロールを表す文字列配列を返します。したがって、最初に、列挙型の項目に一致する配列内のすべての文字列を変換する必要があります。最後に、一致するものを探します。一致する場合は、ユーザーが承認されます。

また、許可されていないユーザーをカスタムの「NotAuthorized」ビューにリダイレクトしていることに注意してください。

クラス全体は次のようになります。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] 
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    /// <summary>
    /// Add the allowed roles to this property.
    /// </summary>
    public Roles Is { get; set; }

    /// <summary>
    /// Checks to see if the user is authenticated and has the
    /// correct role to access a particular view.
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException("httpContext");

        if (!httpContext.User.Identity.IsAuthenticated)
            return false;

        var iCustomPrincipal = (ICustomPrincipal) httpContext.User;

        var roles = iCustomPrincipal.CustomIdentity
                        .GetGroups()
                        .Select(s => Enum.Parse(typeof (Roles), s))
                        .ToArray();

        if (Is != 0 && !roles.Cast<Roles>().Any(role => ((Is & role) == role)))
        {
            return false;
        }

        return true;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext == null)
            throw new ArgumentNullException("filterContext");

        filterContext.Result = new ViewResult { ViewName = "NotAuthorized" };
    } 
}
于 2011-09-15T20:31:40.140 に答える
-1

または、次のように連結できます。

[Authorize(Roles = Common.Lookup.Item.SecurityRole.Administrator + "," + Common.Lookup.Item.SecurityRole.Intake)]
于 2009-07-25T02:47:30.717 に答える