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!
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.
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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With