MVC [Autorize] plus Roles from string - model-view-controller

Hey I got some idea but problem is i can't make this work.
in MVC we can use [Authorize] to "protect" some actions/controllers, we can make next step and give some persmission for a Roles and Users.
[Authorize(Roles="Boss", User="Secretary"]
This working good but its kind of bad becaue in real life we dont know who will have rights for this. So idea was make strings of Roles and Users and back to authorize to make Microsoft magic on this.
[Authoize(Role=RoleString(), User=UserString())]
Ofcourse, its not working, how make this work?

The problem is that AuthorizeAttribute expects a constant for both the User and the Role strings. You will need to make a CustomAuthorizeAttribute that is something like what is found in this blog post.
So lets say you have a string that you store in your web.config that is something like this:
<add key="authorizedUsers" value="Dave,Chuck,Sally" />
and then you have your custom authorize attribute that would be something like this:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public IAuthorizationService _authorizationService { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var user = httpContext.User;
if (!user.Identity.IsAuthenticated)
{
return false;
}
var users = System.Configuration.ConfigurationManager.AppSettings["authorizedUsers"].Split(',');
if users.Contains(user.Identity.Name)
{
return true;
}
return _authorizationService.Authorize(httpContext);
}
}
Note that I threw this together rather quickly so it is not tested. You can easily modify this to get user or group names from a database so that it can be fully dynamic.

Related

ASP.NET Core 2.2 - Action Filter db Query Question

I have users in our app, who are mapped to companies. When a user logs in and starts to make requests I want a way to validate if that user is currently mapped to the company for access to company resources.
The idea I had was to create a whole controller just to manage all of this, but someone mentioned ActionFilters as a much better and cleaner option, I have to agree after looking at it.
The idea is to have the controller setup as:
controller - action - CompanyId - ReportId
So any request to root the system would just look up if there are any companies mapped to that logged in user.
But if the request included CompanyId then they'd go to that company's “portal” account page. It's really any request that includes CompanyId where I want the actionFilter to make a determination on if that user is allowed access.
Request comes in...
There is a CompanyId in the request!
ActionFilter:
Look up in db for all users assigned to that CompanyId. Is current user within that list? No? = kick'em out.
I tried to type in a code example, but the system told me to manually indent each line by 4 spaces, I was doing it from memory anyways so no idea how helpful it would have been anyways.
You could get your action parameters in your action filter and then get your database via HttpContext.RequestServices.GetRequiredService<ApplicationDbContext>().Refer to here.
public class TestActionFilter:Attribute,IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
//If companyId is action parameter
var companyId= context.ActionArguments["companyId"].ToString();
//If companyId1 is query string
var companyId1= context.HttpContext.Request.Query["companyId1"].ToString();
//If companyId2 is in request header
var companyId2= context.HttpContext.Request.Headers["companyId2"].ToString();
//get your dbcontext
var db = context.HttpContext.RequestServices.GetRequiredService<ApplicationDbContext>();
//EF core logic
//...
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
}
You could use it on action directly using [TestActionFilter] attribute or set as global filter
services.AddMvc(options =>
{
options.Filters.Add(new TestActionFilter()); // an instance
});

Global redirect based on logic in ASP.NET MVC3

I am building an ASP.NET MVC3 computer support ticketing portal.
There is a maintenance state, where it is best to forbid the users from interacting with EF/Database, to avoid "collisions" I am currently getting.
I have an IMaintenanceDispatcher that has a boolean property IsOnMaintenance set to true by the business logic, whenever a background logic puts the portal in that state.
I need to redirect client requests to a parking page for the time of maintenance.
Where do I place the logic that will check if the IsOnMaintenance is true, and if so, do a redirect to a URL?
You could put it in an ActionFilterAttribute and apply that attribute to any applicable actions/controllers or globally.
public class IsOnMaintenanceAttribute : ActionFilterAttribute
{
//You'll need to setup your IoC to inject this
public IMaintenanceDispatcher InjectedMaintenanceDispatcher { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
object ticketIdObj;
if (!filterContext.ActionParameters.TryGetValue("ticketId", out ticketIdObj))
return;
//Make sure it exists
if (InjectedMaintenanceDispatcher.IsOnMaintenance(int.parse(ticketIdObj)))
{
var routeValues = new RouteValueDictionary(new {
action = "parkingpage",
controller = "maintenance",
area = "ticket" });
filterContext.Result = new RedirectToRouteResult(routeValues);
return;
}
}
}
Note, your action method parameters needs to contain a variable named ticketId for the filterContext.ActionParameters.TryGetValue to work.
Note: I had assumed that an individual ticket is put into maintenance mode and you were wanting to check for that... but re-reading the question it seems like you want to put the whole area/site on hold. Even with that case, the ActionFilterAttribute example still holds... just not as different.

How do I handle a HttpRequestValidationException and return a meaningful error using AddModelError?

I would like to handle HttpRequestValidationExceptions (e.g. when html is inserted into form fields) and return the user back to the page after submission with a meaningful error to highlight the problem.
For example, on a login page, if the user types some invalid characters into the username field, then I would like to catch the HttpRequestValidationException and return the user to the login page with the username field highlighted.
I can catch the error in a class inheriting from HandleErrorAttribute using the OnException method.
Is there a way from here (or any other way) that I can get the Controller *ModelState* to add the error?
Note: I do not want to turn validation off or redirect to an error page.
e.g.:
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception is HttpRequestValidationException)
{
ModelStateDictionary ModelState = <...>
ModelState.AddModelError("Error", "Invalid chars");
filterContext.HttpContext.Response
filterContext.ExceptionHandled = true;
HttpContextBase HttpContext = filterContext.HttpContext;
HttpContext.Response.Redirect(HttpContext.Request.Path);
return;
}
}
Thanks in advance for any help you can give me!
Instead of capturing and handling the HttpRequestValidationException, you could decorate your model's properties with the [AllowHtml] data annotation and your own custom data annotation, which contains the validation rules you require. See this answer for a good example.
Your model's properties may look like this:
[AllowHtml]
[DisallowHtml]
public string SomeProperty{ get; set; }
Which looks a bit silly, but so far it's the cleanest solution I've encountered.

Conditional ASP.NET MVC 3 Routing (With Areas)

Hurro.
I'm trying to achieve some conditional routing based on whether the current user is an admin or not. The system only has two modes, admin or non-admin and nothing more than this. I'm using areas for my admin area because the controller names would be the same, but they'll deliver different functionality pretty much in every case.
In this system, however, the admins shouldn't really be aware of their admin location, they just know that they use the system to do something else other than what regular users do. I don't want there to be any distinction between the two in terms of URL because of this. What I want to do is be able to do something like mysite.com/AuditHistory and dependant on whether you're an admin or user will depend on what controller is used. So if it's a user making this request, then it'd use the AuditHistoryController in the regular controllers folder, but if it's an admin then it'd use the AuditHistoryController in Areas/Admin/Controllers.
I've seen the use of IRouteConstraint and can do something along the following lines:
public class AdminRouteConstraint : IRouteConstraint
{
public AdminRouteConstraint() { }
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return httpContext.User.IsInRole("Admin");
}
}
With the following:
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", controller = "Home", id = UrlParameter.Optional },
new { controller = new AdminRouteConstraint() }
);
Can I simply get rid of "Admin/" at the front and do the same thing for the other routes but say UserRouteConstraint? I've not seen this done anywhere though and not sure if it's correct.
Any ideas on how to do this?
Could you simply redirect the user from the ActionResult if they are in a role? That is if you don't mind the URL changing?
Something like this...
[Authorize]
public ActionResult AuditHistory()
{
if(Context.User.IsInRole("Admin")
{
return Redirect("Admin/AuditHistory");
}
else
{
return View();
}
}
To me, this is a bit of a hack. But it may be a solution.
Obviously, you would need to do basic checks like making sure the current request is authenticated etc.
If you really don't want the URL to change, you could possibly have two separate views and do away with the admin Area
[Authorize]
public ActionResult AuditHistory()
{
if(Context.User.IsInRole("Admin")
{
return View("AdminAuditHistory", new AdminAuditHistoryViewModel());
}
else
{
return View("AuditHistory", new AuditHistoryViewModel());
}
}
In fact I think this is probably the cleanest solution, but is possibly still a bit of a hack.
I hope this helps.

MVC Routes based on POST parameters

We have an a PHP application that we are converting to MVC. The goal is to have the application remain identical in terms of URLs and HTML (SEO and the like + PHP site is still being worked on). We have a booking process made of 3 views and in the current PHP site, all these view post back to the same URL, sending a hidden field to differentiate which page/step in the booking process is being sent back (data between pages is stored in state as the query is built up).
To replicate this in MVC, we could have a single action method that all 3 pages post to, with a single binder that only populates a portion of the model depending on which page it was posted from, and the controller looks at the model and decides what stage is next in the booking process. Or if this is possible (and this is my question), set up a route that can read the POST parameters and based on the values of the POST parameters, route to a differen action method.
As far as i understand there is no support for this in MVC routing as it stands (but i would love to be wrong on this), so where would i need to look at extending MVC in order to support this? (i think multiple action methods is cleaner somehow).
Your help would be much appreciated.
I have come upon two solutions, one devised by someone I work with and then another more elegant solution by me!
The first solution was to specify a class that extends MVcRouteHandler for the specified route. This route handler could examine the route in Form of the HttpContext, read the Form data and then update the RouteData in the RequestContext.
MapRoute(routes,
"Book",
"{locale}/book",
new { controller = "Reservation", action = "Index" }).RouteHandler = new ReservationRouteHandler();
The ReservationRouteHandler looks like this:
public class ReservationRouteHandler: MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var request = requestContext.HttpContext.Request;
// First attempt to match one of the posted tab types
var action = ReservationNavigationHandler.GetActionFromPostData(request);
requestContext.RouteData.Values["action"] = action.ActionName;
requestContext.RouteData.Values["viewStage"] = action.ViewStage;
return base.GetHttpHandler(requestContext);
}
The NavigationHandler actually does the job of looking in the form data but you get the idea.
This solution works, however, it feels a bit clunky and from looking at the controller class you would never know this was happening and wouldn't realise why en-gb/book would point to different methods, not to mention that this doesn't really feel that reusable.
A better solution is to have overloaded methods on the controller i.e. they are all called book in this case and then define your own custome ActionMethodSelectorAttribute. This is what the HttpPost Attribute derives from.
public class FormPostFilterAttribute : ActionMethodSelectorAttribute
{
private readonly string _elementId;
private readonly string _requiredValue;
public FormPostFilterAttribute(string elementId, string requiredValue)
{
_elementId = elementId;
_requiredValue = requiredValue;
}
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
if (string.IsNullOrEmpty(controllerContext.HttpContext.Request.Form[_elementId]))
{
return false;
}
if (controllerContext.HttpContext.Request.Form[_elementId] != _requiredValue)
{
return false;
}
return true;
}
}
MVC calls this class when it tries to resolve the correct action method on a controller given a URL. We then declare the action methods as follows:
public ActionResult Book(HotelSummaryPostData hotelSummary)
{
return View("CustomerDetails");
}
[FormFieldFilter("stepID", "1")]
public ActionResult Book(YourDetailsPostData yourDetails, RequestedViewPostData requestedView)
{
return View(requestedView.RequestedView);
}
[FormFieldFilter("stepID", "2")]
public ActionResult Book(RoomDetailsPostData roomDetails, RequestedViewPostData requestedView)
{
return View(requestedView.RequestedView);
}
[HttpGet]
public ActionResult Book()
{
return View();
}
We have to define the hidden field stepID on the different pages so that when the forms on these pages post back to the common URL the SelectorAttributes correctly determines which action method to invoke. I was suprised that it correctly selects an action method when an identically named method exists with not attribute set, but also glad.
I haven't looked into whether you can stack these method selectors, i imagine that you can though which would make this a pretty damn cool feature in MVC.
I hope this answer is of some use to somebody other than me. :)

Resources