Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom Authorize attribute for roles as well as a specific user?

I have my Action Method

[Authorize(Roles="Admin")] public ActionResult EditPosts(int id) {     return View(); } 

In my case I need to authorize administrators so they can edit posts but (here comes the cool part), I also need to allow the creator of the post to be able to edit the post which is a normal user. So how can I filter out the user that created the post as well as the admins but leave the others unauthorized? I am receiving the PostEntry id as a route parameter but that's after the attribute and also attributes only accept constant parameters, looks like something very difficult, your answers are highly appreciated, Cheers!

like image 373
Freeman Avatar asked Jul 15 '12 17:07

Freeman


People also ask

Where can the Authorize attribute can be applied?

You can place the Authorize attribute on a controller or on individual actions inside the controller. When we place the Authorize attribute on the controller itself, the authorize attribute applies to all of the actions inside.

How does role based authorization work?

Role-based authorization checks specify which roles which the current user must be a member of to access the requested resource. The controller SalaryController is only accessible by users who are members of the HRManager role or the Finance role.


1 Answers

You could write a custom authorize attribute:

public class AuthorizeAdminOrOwnerOfPostAttribute : AuthorizeAttribute {     protected override bool AuthorizeCore(HttpContextBase httpContext)     {         var authorized = base.AuthorizeCore(httpContext);         if (!authorized)         {             // The user is not authenticated             return false;         }          var user = httpContext.User;         if (user.IsInRole("Admin"))         {             // Administrator => let him in             return true;         }          var rd = httpContext.Request.RequestContext.RouteData;         var id = rd.Values["id"] as string;         if (string.IsNullOrEmpty(id))         {             // No id was specified => we do not allow access             return false;         }          return IsOwnerOfPost(user.Identity.Name, id);     }      private bool IsOwnerOfPost(string username, string postId)     {         // TODO: you know what to do here         throw new NotImplementedException();     } } 

and then decorate your controller action with it:

[AuthorizeAdminOrOwnerOfPost] public ActionResult EditPosts(int id) {     return View(); } 
like image 164
Darin Dimitrov Avatar answered Sep 23 '22 05:09

Darin Dimitrov