I have a web application which is secured down by Windows authentication. However, I have one controller which needs to be available globally to anyone, so they do not need a Windows account on the server to be granted access.
I have got this to work by enabling both Windows authentication, and Anonymous Authentication in IIS. My controllers now look like this:
[Authorize]
public class MyController : Controller
{
public Index()
{
}
public DoStuff()
{
}
etc...
}
My anonymous controller is the same, except I have removed the [Authorise] attribute from the start of it.
Am I right in saying that this instructs the web application to only allow those users with a Windows account to use the majority of controllers, except for the controller which I want to allow anonymous access to?
It seems to work just fine, but I wanted to ensure I have not left a gaping security hole open by doing this?
Are there any issues with enabling both methods of authentication, and setting the application up in this way?
First of all, the way you are doing it, there is no gaping hole in the security of your application and it will behave the way you are anticipating. But there is a better way ...
The problem with Authorize attribute is that it's easy to forget to the new controller you add to your application and if you don't add it, your controller is open to the public.
If you were using MVC 4, you could add the Authorize attribute as a global filter and then use AllowAnonymous attribute on your anonymous controller(s) because Authorize attribute respects AllowAnonymous attribute by Default. MVC 3, on the other hand, doesn't ship with AllowAnonymous attribute. T
The way around is to create the AllowAnonymous attribute yourself in your project like so:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class AllowAnonymousAttribute : Attribute { }
Now, you can subclass from the built in Authorize attribute to customize that and look for Anonymous attribute applied to your controller. If you find the attribute, you can skip the authorization. Here is an example implementation:
public sealed class AuthorizeWithAnonymousSupportAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
if (!skipAuthorization)
{
base.OnAuthorization(filterContext);
}
}
}
You will have to add this attribute to the global filters of your site. In your Global.asax:
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new AuthorizeWithAnonymousSupportAttribute ());
filters.Add(new HandleErrorAttribute());
}
Now, the last step. You can simply add the AllowAnonymous attribute to any controller you want to be anonymous:
[AllowAnonymous]
public class MyController : Controller
{
public Index()
{
}
public DoStuff()
{
}
etc...
}
The benefit of doing all of the above is that you don't have to worry about putting Authorize attribute to the controllers you add to your application. Instead, you will have to explicitly tell the application which controllers are open to the public.
Thanks and hope this helps.
Related
I have a project layout like:
Areas | Admin
Areas | FrontEnd
I want to [Authorize] users per area (as Admin will use a different table to users in FrontEnd. When I use the [Authorize] tag in a Controller in my Admin area, it redirects me to the forms authentication login url which is set in the root web.config file.
Is it possible to override this per area? I see each area has a Web.config file but it seems to ignore the forms authentication setting if I add it in there.
If I am approaching this in the wrong way, I am happy to take some advice.
Edit:
I have tried something but don't know if it's best practice. Basically, implement my own CustomAuth attribute and redirect:
public class CustomAuth : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!base.AuthorizeCore(httpContext))
httpContext.Response.Redirect("~/Admin/Account");
return true;
}
}
Is this a valid approach?
I ended up going with my own [Authorise] attribute and redirecting on Unauthorised access.
public class AuthorizeArea : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectResult("/Admin/Account");
}
}
I've seen that the AuthoriseAttribute can work for each individual controller, what i would like to do is set the entire site permissions to one AD group, is that easy to do or should i just copy and paste the authattrib line to each controller?
Thanks
As #asawyer mentioned using global filter for your case is good practise. For another part of your question in comment: in the global filter where do i specify what AD groups are allowed to use the site? you can specify roles in OnAuthorization method of your custom authorize attribute, smth like:
public class MyAuthAttribute: AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
Roles = 'ad role1, ad role2...'; //Roles is AuthorizeAttribute member
base.OnAuthorization(filterContext);
}
}
and than use it like:
GlobalFilterCollection.Add(new MyAuthAttribute());
in global.asax or w/e else
How can I ensure that information isn't returned from a webmethod or mvc action by just anyone calling it from Jquery/Ajax call/HTTP post get (you get the idea).
Previously I would have used session variables or the view state to do this on every call, is this still possible. Can anyone point me to any good demos around making these calls secure, I've seen a few but they are easy to spoof or work around.
Thanks!
You can use the AuthorizeAttribute as an action filter to filter access to your controllers. You can just add this attribute to the controllers you want to limit the access to. I think the msdn has a good example for this:
http://msdn.microsoft.com/en-us/library/dd381413(v=vs.90).aspx
You can also use Session in this case.
1. create a ActionFilterAttribute class named, e.g., LoginFilterAttribute.
public sealed class LoginFilterAttribute:ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//check if the user is logged in
if (Session["UserSessionKey"]==null)
//redirect to login page or do nothing
else
//return data or do something else
}
}
2. in your action, put this attribute before the action method
[LoginFilter]
public ActionResult ActionNeedLogin()
{
return View();
}
or, register the attribute in global.asax to keep all action from anonymouse access.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyHandleErrorAttribute());
filters.Add(new LoginFilterAttribute());
}
Given an ASP.NET MVC Controller class declaration:
public class ItemController : Controller
{
public ActionResult Index()
{
// ...
}
public ActionResult Details()
{
// ...
}
[Authorize(Roles="Admin, Editor")]
public ActionResult Edit()
{
// ...
}
[Authorize(Roles="Admin")]
public ActionResult Delete()
{
// ..
}
}
I need to reflect a list of methods in this class which may be invoked with the current user's permissions.
Please share some ideas of what could be done in this case.
Well for the new question think something along the lines of:
new ReflectedControllerDescriptor(typeof(ItemController)).GetCanonicalActions()
could be used to return the list of all available actions. I don't have ASP.NET MVC available to me at work, so I can't really check to see if the ActionDescriptor's returned by that will contain some parameter which says which members are allowed to execute them.
http://msdn.microsoft.com/en-us/library/system.web.mvc.actiondescriptor_members%28v=VS.90%29.aspx
That is the members of the ActionDescriptor, you might be able to find something in there. I'll see tonight if I can figure it out, this has gotten me kind of intrigued.
There's no universal user login/authentication system for all applications, thus this really isn't possible to create a 'universal solution'. You could create your own user login and authorization classes which you then add your own annotations to methods to do, but its going to have the same restrictions that the asp.net mvc system has, its only for your login/authorization system (or whoever extends that system).
I started off using the default project's AccountController, but I've extended/changed it beyond recognition. However, in common with the original I have a LogOn and LogOff action.
Clearly, the LogOn action must be accessible to everyone. However, since I've added lots of other actions to this controller (to create & edit users), I want 99% of the actions to require administrator role membership.
I could decorate all my actions with [Authorize Roles="Administrators"] but there's a risk I'll forget one. I'd rather make it secure by default, by decorating the controller class itself with that attribute, and then relax the requirement on my LogOn method. Can I do that?
(As in, can I do that out-of-the-box without creating custom classes, etc. I don't want to complicate things more than necessary.)
To override an controller Attribute at the Action level you have to create a custom Attribute and then set the Order property of your custom attribute to a higher value than the controller AuthorizeAttribute. I believe both attributes are then still executed unless your custom attribute generates a result with immediate effect such as redirecting.
See Overriding controller AuthorizeAttribute for just one action for more information.
So I believe in your case you will just have to add the AuthorizeAttribute on the Actions and not at the controller level. You could however create a unit test to ensure that all Actions (apart from LogOn) have an AuthorizeAttribute
You can use AuthorizeAttribute on your class
http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx
For relaxing you can implement for example a custom action filter attribute like this (I didn' test if it works).
public class GetRidOfAutorizationAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
// you can for example do nothing
filterContext.Result = new EmptyResult();
}
}
After way too much time, I came up with a solution.
public class OverridableAuthorize : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
var action = filterContext.ActionDescriptor;
if(action.IsDefined(typeof(IgnoreAuthorization), true)) return;
var controller = action.ControllerDescriptor;
if(controller.IsDefined(typeof(IgnoreAuthorization), true)) return;
base.OnAuthorization(filterContext);
}
}
Which can be paired with IgnoreAuthorization on an Action
public class IgnoreAuthorization : Attribute
{
}