Reputation: 3707
I want that when a non logged in user tries to access any controller that isn't specifically allowed for non logged in users, the user get's redirected to a controller to handle logon. How can i accomplish that in the best way? Thought it would be nice to do it in Global.asax.cs somehow, right?
Upvotes: 1
Views: 279
Reputation:
Inherit all your controllers from a base controller. Base controller should have an annotation above class declaration. You can use a .NET annotations such as [Authorize], or you can implement your own annotation, which is straight forward.
E.g.
[Secure()]
public class BaseController : Controller
{
// Action methods
}
You will then create controllers that will derive from your base controller:
[Secure(false)]
public class NonSecureController: BaseController
{
// Action methods
}
You will have to implement simple annotation to which you can pass a flag to indicate whether user is required to be logged in or not.
When developing a custom attribute (annotation), you can specify its scope to be either class or method. This means that you'll have a more granular control over your permissions logic.
Upvotes: 0
Reputation: 719
The easiest step to take when securing an ASP.NET MVC3 application is to require that the users be logged in to access specific URLS. This is done by using the Authorize filter [Authorize()] on a controller or action.
http://build.mt.gov/2011/10/27/aspnet-mvc3-and-the-authorize-attribute.aspx
Customize Authorize Attribute:
http://www.diaryofaninja.com/blog/2011/07/24/writing-your-own-custom-aspnet-mvc-authorize-attributes
Upvotes: 1
Reputation: 81660
Use [Authorize] attribute. It works fine with Forms Authentication which I suppose is what you are using.
Upvotes: 4