Securing ajax calls in a ASP.NET MVC application - asp.net

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

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

Need to restrict AD users - Windows Authentication in ASP.NET

I have a website which uses Windows Authentication. I need to restrict access to only a few users, who are present in a local database. How can I achieve it? Example DB has "domain\user1", only user1 should be allowed. "domain\user2" should not be allowed.
Thanks in advance
in your controller class, you can use the [Authorize] attribute to restrict access.
If you use it by itself, then you restrict the entire controller to only authenticated users.
If you want specific users to access a controller, you can add parameters to the Authorize attribute, such as:
[Authorize(Roles ="Administrators")]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
In the example above, I'm restricting the use of the homecontroller to administrators only, I can also give access only to specific users:
[Authorize(Users = "user1")]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
You can also apply this to specific methods in your controller

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

ASP MVC Authorize all actions except a few

I have a controller and I would like to require Authorization for all actions by default except a couple. So in the example below all actions should require authentication except the Index. I don't want to decorate every action with the Authorize, I just want to override the default authorization in certain circumstances probably with a custom filter such as NotAuthorize.
[Authorize]
public class HomeController : BaseController
{
[NotAuthorize]
public ActionResult Index()
{
// This one wont
return View();
}
public ActionResult About()
{
// This action will require authorization
return View();
}
}
Ok, this is what I did. If there is a better way let me know.
public class NotAuthorizeAttribute : FilterAttribute
{
// Does nothing, just used for decoration
}
public class BaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Check if this action has NotAuthorizeAttribute
object[] attributes = filterContext.ActionDescriptor.GetCustomAttributes(true);
if (attributes.Any(a => a is NotAuthorizeAttribute)) return;
// Must login
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
}
What about [AllowAnonymous] ??
MVC4 has a new attribute exactly meant for this [AllowAnonymous] (as pointed out by Enrico)
[AllowAnonymous]
public ActionResult Register()
Read all about it here:
http://blogs.msdn.com/b/rickandy/archive/2012/03/23/securing-your-asp-net-mvc-4-app-and-the-new-allowanonymous-attribute.aspx
Here's what I would do, similar to Craig's answer with a couple of changes:
1) Create an ordinary attribute deriving from System.Attribute (no need to derive from FilterAttribute since you aren't going to be using anything FilterAttribute provides).
Maybe create a class hierarchy of attributes so you can test based on the hierarchy, e.g.
Attribute
AuthorizationAttribute
AuthorizationNotRequiredAttribute
AuthorizationAdminUserRequiredAttribute
AuthorizationSuperUserRequiredAttribute
2) In your BaseController override the OnAuthorization method rather than the OnActionExecuting method:
protected override void OnAuthorization(AuthorizationContext filterContext)
{
var authorizationAttributes = filterContext.ActionDescriptor.GetCustomAttributes(true).OfType<AuthorizationAttribute>();
bool accountRequired = !authorizationAttributes.Any(aa => aa is AuthorizationNotRequiredAttribute);
I like the approach of being secure by default: even if you forget to put an attribute on the Action it will at least require a user to be logged in.
Use a custom filter as described in Securing your ASP.NET MVC 3 Application.
Mark the controller with [Authorize]
[Authorize]
public class YourController : ApiController
Mark actions you want public with :
[AllowAnonymous]
Little late to the party, but I ended up creating a Controller-level auth attribute and an Action-level auth attribute and just skipping over the Controller auth if the Action had its own Auth attribute. See code here:
https://gist.github.com/948822

Resources