これが私のバージョンで、@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;
}
}