0

Authorize次のように、コントローラーまたはアクションで属性を使用します。

[Authorize(Roles="admin,user", Users="user1,user2")]
public ActionResult LogOn(LogOnModel model, string returnUrl) {
    return view();
}

[Authorize(Roles="admin,user",Users="user1")]ただし、すべてのコントローラーまたはアクションでこのように定義する必要があります。

これを1つの場所/ファイルで定義するにはどうすればよいですか?

RegisterGlobalFiltersこれを行いますか?[Authorize(Roles="*",Users="*")]グローバル フィルターを使用して定義する方法がわかりません。

4

1 に答える 1

1

これを試して

新しいファイルを作成し、アクションでこの属性ヘッダーを使用します

public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
   private readonly RoleEnum[] _acceptedRoles;


public AuthorizeAttribute(params RoleEnum[] acceptedroles)
{
    _acceptedRoles = acceptedroles;
}

public AuthorizeAttribute(params bool[] allowAll)
{
    if (allowAll[0])
        _acceptedRoles = new RoleEnum[] { RoleEnum.Admin, RoleEnum.user};
}

public void OnAuthorization(AuthorizationContext filterContext)
{
    if (SessionHelper.UserInSession == null)//user not logged in
    {
        FormsAuthentication.SignOut();
        filterContext.Result =
             new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary {{ "controller", "Home" },
                                         { "action", "Index" },
                                         { "returnUrl",    filterContext.HttpContext.Request.RawUrl } });//send the user to login page with return url
        return;
    }
    if (!_acceptedRoles.Any(acceptedRole => SessionHelper.UserInSession.UserRoles.Any(currentRole => acceptedRole == currentRole.Role)))
        //allow if any of the user roles is among accepted roles. Else redirect to login page
        throw new UnauthorizedAccessException();

 }
}

これはリターン URL でも機能します。

参照

于 2013-04-13T03:47:08.303 に答える