Reputation: 4084
How do I achieve authorization with MVC asp.net?
Upvotes: 32
Views: 51653
Reputation: 359
This is how you can have authentication by default: http://mycodepad.wordpress.com/2014/03/17/mvc-secure-your-web-app/
Upvotes: 0
Reputation: 21
I would recommend to take a look at this article: http://kbochevski.blogspot.com/2009/11/mvc-forms-authentication-and.html
It helped me today.
Upvotes: 2
Reputation: 29375
Use the Authorize attribute
[Authorize]
public ActionResult MyAction()
{
//stuff
}
You can also use this on the controller. Can pass in users or roles too.
If you want something with a little more control, you could try something like this.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
string[] users = Users.Split(',');
if (!httpContext.User.Identity.IsAuthenticated)
return false;
if (users.Length > 0 &&
!users.Contains(httpContext.User.Identity.Name,
StringComparer.OrdinalIgnoreCase))
return false;
return true;
}
}
Upvotes: 54
Reputation: 676
There is an Authorization feature with MVC, using ASP.NET MVC beta and creating the MVC project from Visual Studio, automatically adds a controller that used authorization. One thing that will help with your google search, is that it is a "filter". So try searching on "Authorization Filter MVC" and anything preview 4 or greater will help.
Upvotes: 4