user3527150
user3527150

Reputation: 926

Check authorize(Role) inside controller in MVC4

I create a controller in my project .

         [Authorize(Roles = "Admin")]
        private StudentRepositor obj = new StudentRepositor();
        public ActionResult Index()
        {

            var model = obj.GetStudentlist();
            foreach (var stu in model)
            {
                stu.State = (stu.State == "1") ? "فعال" : "غیرفعال ";
            }
            return View(model);
        }

I want to check the permission inside my controller not outside .

For example some thing like this :

 public ActionResult Index()
            {

               if(Role=admin) return view2
               if(role=teacher) return view1
            }

Can i do something like this ?!!

Best regards

Upvotes: 1

Views: 5243

Answers (2)

Tobias
Tobias

Reputation: 2840

You should be able to use User.IsInRole()

 public ActionResult Index()
        {

           if(User.IsInRole("admin")) 
           {
               //Return View
           }
           else if(User.IsInRole("teacher")) 
           {
               //Return View
           }
           else
           {
               //Return View
           }
        }

Upvotes: 6

leskovar
leskovar

Reputation: 661

I suggest you create your custom AuthorizationAttribute, something like this.

public class AuthorizationAttribute : FilterAttribute, IAuthorizationFilter
    {
        private readonly Type _userType;

        public AuthorizationAttribute()
        {
        }

        public AuthorizationAttribute(Type userType)
        {
            _userType = userType;
        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var currentHttpContext = filterContext.RequestContext.HttpContext;
            if (!currentHttpContext.User.Identity.IsAuthenticated)
            {
                //Redirect 
            }

            if (_userType != null)
            {
                var identity = filterContext.RequestContext.HttpContext.User.Identity.Name;
                //Get type for identity

                if(_userType != identityType)
                {
                     //Redirect
                }

            }
        }
    }

After that you can use it like this:

[Authorization(typeof(Admin))]
public ActionResult Create()
{}

Upvotes: 0

Related Questions