Asp.Net Mvc Identity Role Management - asp.net-mvc

I am using Identity in my MVC project. Nowadays, i am trying to develop my authentication system and implement group-based identity.
I wonder what the way is, are you following to manage roles. IE. i have an action in one of my controller and named, CreateNewStudent. I am creating new role names, CanCreateStudent and write the related action filter, top of my action.
Is that the only way ? Should i need to put action filters one by one ?
Regards.

You could also have those attributes on controllers. In the code below for example, if the controller inherited from the base, the actions inside of that will require authentication. You can add roles in there.
[Authorize]
public class BaseController : Controller
{
//do some common operations
}
public class HomeController : BaseController
{
public virtual ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
}

Related

ASP.NET-MVC 3 force log for every page

I'm new to ASP.NET and not the most experienced of programmers.
I have recently been introduced to ASP.NET-MVC 3 for an application I'd like to build.
I have the basic functionality down but am not to familiar with the login.
The built-in login works for what I want (just something simple), but I want to ensure that a login must be used before any of the actual functionality appears.
What would be the best way of doing this?
Any help would be greatly appreciated.
in your controller you should make use of the Authorize attribute, this forces the authorization before doing the decorated action.
For instance, in your home controller add the following [Authorize] as such
[Authorize]
public ViewResult Index()
{
return View();
}
Also you can decorate an entire controller which will force ALL methods to be authroized prior to being used, as such:
[Authorize]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}

MVC 3 anoNynmous and Windows authentication combined

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.

ASP.NET MVC security: how to check if a controller method is allowed to execute under current user's perrmissions

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).

ASP.NET MVC: Can I say [Authorize Roles="Administrators"] on the Controller class, but have one public action?

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
{
}

ASP.NET MVC Account Controller usage guidelines?

I'm looking at the MVC account controller, and it seems to be from ASP.NET webforms. Is there any good background information on how to use it?
Can you map it to a user database table or is it better to roll your own user management?
How do you make use of it in MVC to restrict what pages a logged in user can view? Do you have to roll all of that on your own?
What resources on the web can help with understanding the ASP.NET Membership?
I'm looking at the MVC account
controller.... it seems to be from
asp.net?
Scott Guthrie explains this quite well in his blog entry about ASP.NET MVC Preview 4. He basically says that the Account Controller from the MVC sample uses the ASP.NET membership provider, so you can use any of those. (I think you can find out more about ASP.NET membership providers on the internet.) If you do not want to implement/use one of those, modifying the application to use your own user management would probably be the best option.
How do you make use of it in MVC to
restrict what pages a logged in user
can view? Do you have to roll all of
that on your own?
You can add the Authorize attribute to the controller class or action method. (Same source as above.)
// Only logged in users can access this controller.
[Authorize]
public class SomeController : Controller
{
#region Not really important for this example. :]
// Maybe rather use a BLL service here instead of the repository from the DAL, but this example is already more verbose than required.
private IStuffRepository stuffRepository;
public SomeController(IStuffRepository stuffRepository)
{
if (null == stuffRepository)
{
throw new ArgumentNullException("stuffRepository");
}
this.stuffRepository = stuffRepository;
}
#endregion
// The authorize attribute is inherited - only logged in users can use the index action.
public ActionResult Index()
{
return View();
}
// Moderators can flag stuff.
[Authorize(Roles="Moderator")]
public ActionResult Flag(int id)
{
this.stuffRepository.Flag(id);
return RedirectToAction("Index");
}
// Admins ans SysOps can delete stuff.
[Authorize(Roles="Admin,SysOp")]
public ActionResult Delete(int id)
{
this.stuffRepository.Delete(id);
return RedirectToAction("Index");
}
// Only joed can change the objects stuff. ;)
// (This is probably bullshit, of course, but I could not make any better example. I blame the fact it is late at night. :))
[Authorize(Users="COMPANY\\joed")]
public ActionResult ChangeId(int oldId, int newId)
{
this.stuffRepository.ChangeId(oldId, newId);
return RedirectToAction("Index");
}
}

Resources