Using [Authorize] without SimpleMembershipProvider

元气小坏坏 提交于 2019-12-04 19:31:45
Selman Genç

You should create your own Authorize attribute by inheriting from AuthorizeAttribute class

public class CustomAuthorizeAttribute : AuthorizeAttribute
{

}

Then you can configure it however you like.

Also you can take a look at these questions on Stackoverflow:

  1. Custom Authorize Attribute
  2. ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

I ran into the same problem and I used a custom attribute. But my roles weren't as sophisticated. I needed to be able to give multiple roles to a user so I just used a string collection to do that. I used this custom filter

CustomAuthorize(UserRole="AUTHORIZED_ROLE");

 public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public string UserRole { get; set; }
        protected IUnitOfWork uow = new UnitOfWork();
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);
            if (!isAuthorized)
            {
                return false;
            }
            var currentUser;//Get Current User 
            if(UserRole==currentUser.Role.Name)
            {
                return true;
            }


        return false;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary(
                        new
                        {//redirect where you want to in case of not authorized.
                            controller = "Home",
                            action = "AccessDenied" 
                        })
                    );
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!