Where should access control logic live in MVC? - asp.net

I'm learning ASP.NET using MVC and code-first entity framework (with razor). I have been finding a lot of conflicting information on the topic and I thought I would turn to the SO community to try to clear some things up.
From Model to Controller to View, where should the access logic live? For example (simplified for this post):
public class EmployeeController : Controller
{
private Repo _repo;
[HttpGet]
public ActionResult Create(int id)
{
Business business = _repo.FindBusiness(id);
if (CurrentUser.UserId == business.GeneralManager.UserId ||
CurrentUser.Father.UserId == business.Owner.UserId)
{
Employee employee = new Employee();
employee.Business = business;
return View();
}
}
[HttpPost]
public ActionResult Create(Employee employee)
{
Business business = _repo.FindBusiness(employee.business.ID);
if (CurrentUser.UserId == business.GeneralManager.UserId ||
CurrentUser.Father.UserId == business.Owner.UserId)
{
_repo.Save(employee);
Return Redirect(...);
}
}
}
Then I want the current user to be able to create a new business if the current user is the general manager of the business or if his dad owns the place. What I mean to point out here is that it's not dependent on the user's role, but instead some business logic for why they can act.
Similarly, I want to be able to show or hide a link in the view base on the same condition eg:
...
#if (CurrentUser.UserId == business.GeneralManager.UserId ||
CurrentUser.Father.UserId == business.Owner.UserId)
{
#Html.ActionLink(...)
}
...
I definitely don't want to do it this way. My question is: if the access logic can be bundled as a single method, where does that method "belong" in mvc? Should it be a readonly property of a ViewModel? Should there be some static access controller? Part of the model itself? Thanks for your attention!

You should use ActionFilters for this, take a look at this example.
Take a look at this answer for authorization also.
After writing your ActionFilter logic, your controller will look like this:
public class EmployeeController : Controller
{
private Repo _repo;
[CustomActionFilter] //your ACL logic will be here.
[HttpGet]
public ActionResult Create(int id)
{
//no acl logic in here.
}
[CustomActionFilter] //your ACL logic will be here.
[HttpPost]
public ActionResult Create(Employee employee)
{
//no acl logic in here.
}
}
The ActionFilters can be applied at the Controller level also.

Related

Automatically load model on each request

Note: Not sure if the following is the right way of doing what I want.
Background: I have a forum (php) and I am creating a asp.net MVC web application that is sort of independent from the forum, except the login data. The user registers and logins through the forum but the app needs to check the login status by reading the session hash from the cookie and comparing it with the forum's database of logged in users.
Objective: I to include my UserModel class on every request to see if the user has certain permissions to do what he's requesting to do. Also for my views to display User related data.
Do I need to manually add something like this to every controller's action in my application?
public ActionResult Index()
{
UserRepository userRep = new UserRepository();
UserModel user = userRep.GetUserBySession(Request.Cookies["userHash"].Value);
//do stuff with user
...
return View(myViewModel);
}
Look at ValidationAttribute. You can roll your own, and have your own custom logic in it:
public class CustomAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
UserRepository userRep = new UserRepository();
UserModel user = userRep.GetUserBySession(Request.Cookies["userHash"].Value);
if (user == null) {
// Redirect to login?
}
}
}
Then you can decorate your methods like this:
[CustomAttribute]
public ActionResult Index()
Or if you will be needing to apply it to every HTTP method in your class, you can decorate it at class level:
[CustomAttribute]
public class MyClass

Accessing AuthorizationAttribute within Controller

I have a custom AuthorizeAttribute written in MVC. I have it applied to a controller for security. In that AuthorizeAttribute class I have written are several variables I gathered from a web service call I would like to access inside the controller to prevent having to call the web service again. Is this possible?
Your best approach would be to use HttpContext.Current.Items for storing those variables because that data will only be valid for a single http request. Something like this:
public class CustomAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.User.Identity == null) return false;
if (!httpContext.Request.IsAuthenticated) return false;
var user = new WSUser(); //get this from your webservice
if(user == null) return false;
httpContext.Items.Add("prop", user.Property);
return user.Authorized;
}
}
public class HomeController : Controller
{
[CustomAuthorize]
public ActionResult Index()
{
var property = (string) HttpContext.Items["prop"];
return View();
}
}
You would also want to encapsulate logic for storing and retrieving items from HttpContext.Current into a separate class to keep the code clean and to follow Single responsibility principle
You could save these variables in a static class to store it. But, a elegant solution would be to have a modelbinder object that you call like parameter in your controller and that read the static class and return the properties that you need.
Perhaps, if you are applying security, the best will be that call the webservices each once.
Reference for your custom model binder

Create/Get DefaultHtmlGenerator from MVC Controller

I am trying to create(Or get an instance of it somehow) for Microsoft.AspNet.Mvc.Rendering.DefaultHtmlGenerator inside my MVC6 controller method
I wanted to generate the html for validation for my Model my self inside my controller of asp.net mvc. My issue is where to get the constructor data for DefaultHtmlGenerator like antiforgery, metadataProvider..etc
[HttpGet]
public IActionResult GetMarkup()
{
// IHtmlGenerator ge = this.CurrentGenerator();
IHtmlGenerator ge = new DefaultHtmlGenerator(params);
var tag= ge.GetClientValidationRules(params)
}
here is the a link about the HtmlGenerator class
DefaultHtmlGenerator
Since MVC 6 is based on dependency injection, all you have to do is require IHtmlGenerator in your constructor, and the DI container will automatically fill in all of the dependencies of DefaultHtmlGenerator (provided that is what is setup in your DI configuration).
public class HomeController : Controller
{
private readonly IHtmlGenerator htmlGenerator;
public HomeController(IHtmlGenerator htmlGenerator)
{
if (htmlGenerator == null)
throw new ArgumentNullException("htmlGenerator");
this.htmlGenerator = htmlGenerator;
}
public IActionResult GetMarkup()
{
// Use the HtmlGenerator as required.
var tag = this.htmlGenerator.GetClientValidationRules(params);
return View();
}
}
That said, it appears that the GetClientValidationRules method is only designed to work within a view, since it accepts ViewContext as a parameter. But this does answer the question that you asked.

Securing ajax calls in a ASP.NET MVC application

I have an ASP.NET MVC based application that allows different levels of access depending on the user. The way it currently works is when a user accesses a page, a check is done against the database to determine the rights that user has. The view is then selected based on the level of access that user has. Some users see more data and have more functionality available to them than do others. Each page also makes a variety of ajax calls to display and update the data displayed on the page.
My question is what is the best way to ensure that a particular ajax call originated from the view and was not crafted manually to return or update data the user does not have access to? I would prefer not to have to go to the database to re-check every time an ajax call is made since that was already done when the user initially loaded the page.
Check out the Authorize Attribute, you can put it on an entire controller or just specific methods within your controller.
Examples:
[Authorize(Roles = "Administrator")]
public class AdminController : Controller
{
//your code here
}
or
public class AdminController : Controller
{
//Available to everyone
public ActionResult Index()
{
return View();
}
//Just available to users in the Administrator role.
[Authorize(Roles = "Administrator")]
public ActionResult AdminOnlyIndex()
{
return View();
}
}
Alternately, you can write a custom Authorize attribute to provide your own logic.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
IPrincipal user = httpContext.User;
var validRoles = Roles.Split(',');//Roles will be a parameter when you use the Attribute
List<String> userRoles = GetRolesFromDb(user);//This will be a call to your database to get the roles the user is in.
return validRoles.Intersect(userRoles).Any();
}
}
To use:
[CustomAuthorizeAttribute(Roles = "Admin,Superuser")]
public class AdminController : Controller {
}
If iyou are using a post use
[Authorize]
[ValidateAntiForgeryToken]
If iyou are using a get use
[Authorize]
You can also use this custom attribute
public class HttpAjaxRequestAttribute : ActionMethodSelectorAttribute
{
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
if (!controllerContext.HttpContext.Request.IsAjaxRequest())
{
throw new Exception("This action " + methodInfo.Name + " can only be called via an Ajax request");
}
return true;
}
}
Then decorate your action as below
[Authorize]
[HttpAjaxRequest]
public ActionResult FillCity(int State)
{
//code here
}
Remember to "Mark/Tick" if this solve your problem.
It depends on what type of session mechanisam you are using . Are you using default membership provider ? If not than you can pass user's id and sessionid make sure that user session is valid and user has required permission to make that call .
Along with the Authorize attribute, you can also allow only Ajax requests using custom attributes as shown here.
Thanks

ASP.NET MVC: Action Filter to set up controller variables?

I have a scenario whereby with every page request I must check the session of the presence of a particular ID. If this is found I must grab a related object from the database and make it available to the controller. If no session ID is found I need to redirect the user (session expired).
At the moment I have a custom chunk of code (couple of lines) that does this at the start of every action method within my controller - which seems like unnecessary repetition.
Is this scenario worthy of an Action Filter?
Thanks
UPDATE
Some great info here guys. Thank you
Yes, this sounds like a good application of an action filter, as you can apply it at the controller level to operate on all actions. You could also make it part of a controller base class, if you didn't want to add it to all controllers manually, or write your own controller factory which automatically applies this action filter to each controller.
See ASP.NET MVC Pass object from Custom Action Filter to Action for passing data from an action filter to an action.
Create a base controller like this
public class MyContollerController : Controller
{
public DataEntity userData;
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
var customId = requestContext.HttpContext.Session["key"];
if(customId!=null)
{
userData=getDataGromDataBase(customId);
}
else
{
//redirect User
}
}
}
Now Create ur controllers like this
public class MyDemoController : MyContollerController
{
public ActionResult Action1()
{
//access your data
this.userData
}
public ActionResult Action2()
{
//access your data
this.userData
}
}
Another way is to do that with Model Binders. Suppose that object is ShoppingCart
//Custom Model Binder
public class ShoppingCarModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
//TODO: retrieve model or return null;
}
}
//register that binder in global.asax in application start
ModelBinders.Binders.Add(typeof(ShoppingCart), new ShoppingCartBinder());
// controller action
public ActionResult DoStuff(ShoppingCart cart)
{
if(cart == null)
{
//whatever you do when cart is null, redirect. etc
}
else
{
// do stuff with cart
}
}
Moreover, this is more unit testable and clear way, as this way action relies on parameters supplied from outside

Resources