Role management in MVC 6 - asp.net-core-mvc

I am looking for role and permission management in MVC6. Basically my requirement is I will be having roles and those roles will have some set of permissions(Like Add,Edit,Delete,Modify etc.).
So, based on this I want to achieve following things
Show/Hide content of view based on role and there permission for user.
To restrict access to controller and its action methods.
Any help on this appreciated !

Partial answer:
2: Just add attributes to your controller and/or methods, e.g.
[Authorize(Roles = "Administrator, PowerUser")]
public class ControlPanelController : Controller
{
public ActionResult SetTime()
{
}
[Authorize(Roles = "Administrator")]
public ActionResult ShutDown()
{
}
}
https://docs.asp.net/en/latest/security/authorization/roles.html

Related

Override controller Authorize attribute for viewresult

If the authorize attribute has been applied to the controller is it possible to allow unauthorized access to an action/viewresult inside that controller?
Say for example I didn't want authorization to occur on Test2 in the following:
[Authorize]
public class TestController : Controller
{
public ViewResult Test()
{
return View();
}
public ViewResult Test2()
{
return View();
}
}
Thanks in advance.
No, this is not possible. You will have to apply the Authorize attribute on the Test action and not on the controller. Another possibility is to put the Test2 action on another controller which is not decorated with this attribute.
Back in MVC 3 it appears it was indeed not possible to do (as mentioned Darin Dimitrov), but if anyone using MVC 4 (and up) comes across this question, he\she should be able to use AllowAnonymous filter to achieve the result. So the code would become:
[Authorize]
public class TestController : Controller
{
public ViewResult Test()
{
return View();
}
[AllowAnonymous]
public ViewResult Test2()
{
return View();
}
}

MVC3 Multi-User Data Level Security

The application I am working on is multi-user and multi-company and I am having trouble at the moment trying to figure out the most efficient/best way to ensure data level security, in broad terms prevent UserA from seeing UserB's data. If there are various controllers (Products, Orders, etc) and models, then the routes are something like Product/Edit/1 and Order/Edit/1. However, to ensure that users cannot alter the routes to see each others data it seems that each service layer/db layer call will require me checking that the specific product key/order key belongs to the authenticated user? Is this the best option or am I missing something more elegant.
Edit Update
From Omri's answer below, the first link actually has a link to here. It mentions the various ways to accomplish the access level security, but I guess this is what I want to know people's opinions about. Should I do something like this:
public class ProductController
{
public ActionResult Edit(int id)
{
if (_productService.CanUserEdit(id, userID))
{
_productService.Save(id);
}
else
{
throw UnauthorizedException;
}
return RedirectToAction("Index");
}
}
OR
public class ProductController
{
public ActionResult Edit(int id)
{
_productService.Save(id, userID);
return RedirectToAction("Index");
}
}
public class ProductService
{
public void Save(int id, int userID)
{
if (CanUserEdit(id, userID))
{
//DO SAVE
}
}
private CanUserEdit(int id, int userID)
{
}
}
Obviously there is not much difference between the two implementations, just whether or not the action takes place within the Controller or at the service level. The service level changes on the fly based on the company, so my guess is that we probably should do the first option and have the product service for each company derive from a common base class that implements the CanUserEdit capability since that does not change.
Seems to be two common approaches: OnActionExecuting or AuthorizeAttribute. See here:
How to Extend/Architect the ASP.NET MVC 3 Authorize Attribute to Handle This Scenario
ASP.NET MVC 3 also has Global Action Filters which allow you to apply action filters globally without the need for explicit attribute declaration:
http://blog.tallan.com/2011/02/04/global-action-filters-in-asp-net-mvc-3/

AD Roles based Authorization in MVC3

In our MVC3 based Intranet app, one AD User may belong to many roles and during login, they will choose the role they want to login as. We are currently authenticating the user using the following approach: http://www.codeproject.com/KB/system/everythingInAD.aspx#35
Once the user is authenticated and found to belong to the role they are trying to login as, we would like to authorize access to specific Controllers and Actions based on their Role. We would prefer to use the Authorize attribute of the MVC.
Since we are not using any providers to autnenticate, can we still somehow use the Authorize attribute to restrict access?
Thanks!
Bala
You can use the Authorize attribute as long as your custom membership provider inherits from the asp.net MemberShipProvider class.
But if you decide to have an entirely new provide which doesn't inherit from asp.net MembershipProvider class than you can't use the Authorize attirbute.
#Pankaj is right but You can define you'r custom Attribute for exam: class MyAuthorizationAttribute : FilterAttribute, IAuthorizationFilter and override OnAuthorization method of it. then decorate each action with this custom attribute and calculate authorization in body of OnAuthorization. this is a sample:
public class MyAuthorizationAttribute : FilterAttribute, IAuthorizationFilter
{
public string _name;
public MyAuthorizationAttribute(string name)
{
this._name = curPerm.name;
}
public void OnAuthorization(AuthorizationContext filterContext)
{
// Calculate permissions...
if (!permit)
{
Exception e = new MethodAccessException("Access to partial denied!");
throw new Exception("Can't access via address bar!", e);
}
}
}
and use in action
[MyAuthorizationAttribute ("Add")]
public ActionResult Index()
{
ViewBag.Message = "About page";
return View();
}
Hope this useful.
Good luck.

Implementing edit action in asp.net mvc 3

I seen many examples of edit actions in asp.net mvc 3 and that's why I confused. For example, how does work UpdateModel and TryUpdateModel methods? Or how to implement edit action if I want to update not all fields?
Could anyone give me a link about implementing edit action in asp.net 3?
Best way to update only desired fields is create separate view model for it. For example, imagine you've got user class like this
public class User
{
public int Id {get;set;}
public string UserName {get;set}
public bool IsAdmin {get;set;}
}
And suppose you do not wish to let user supply value for IsAdmin property. You create view model like this (no IsAdmin field)
public class EditUserViewModel
{
public int Id {get;set;}
public string UserName {get;set}
}
And the edit action pseudo something
public ActionResult Edit(EdituserViewModel model)
{
If(ModelState.IsValid)
{
User user = _repository.GetUser(model.Id);
user.UserName = model.UserName;
_repository.Update(user);
return RedirectToAction("Index");
}
return View(model);
}
This way, there's no possiblity to supply IsAdmin from client side. You may also want to take a look at AutoMapper and Jimmy Bogard's blog for mapping view models to domain models. Jimmy's got the post about using ViewModels and AutoMapper in asp.net mvc too.

Apply AuthorizeAttribute to a controller class and to action simultaneously

Is There one way to make a [Authorize] attibute be ignored in one action in a controller class that has a Authorize attribute?
[Authorize]
public class MyController : Controller
{
[Authorize(Users="?")]//I tried to do that and with "*", but unsuccessfuly,
public ActionResult PublicMethod()
{
//some code
}
public ActionResult PrivateMethod()
{
//some code
}
}
Just the PrivateMethod() should have authentication required, but it has been required too.
PS: I wouldn't like to make my custom authorize filter.
[]'s
You can use [AllowAnonymous]
[Authorize]
public class MyController : Controller
{
[AllowAnonymous]
public ActionResult PublicMethod()
{
//some code
}
public ActionResult PrivateMethod()
{
//some code
}
}
By default it's impossible - if you set [Authorize] for controller then only authenticated user can access to action.
or
You can try custom decisions: stackoverflow.
A solution is in this article: Securing your ASP.NET MVC 3 Application
The article talks about a white list approach where you decorate actions with a AllowAnonymous custom attribute. It requires that you extend AuthorizeAttribute and the OnAuthorization method to skip authorization checks of AllowAnonymous -actions. (The approach is credited to Levi, a security expert on the MVC team.)
public class MyController : Controller
{
[Authorize] //it will only work for the following action
public ActionResult PublicMethod()
{
//some code
}
public ActionResult PrivateMethod() //[Authorize] will not work for this action
{
//some code
}
}
Just for future reference This is now available to be done by the the [AllowAnonymous] attribute in ASP.NET MVC 4.
More Info

Resources