How do I achieve authorization with MVC asp.net?
4 Answers
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; } } Comments
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.
5 Comments
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.
Comments
This is how you can have authentication by default: http://mycodepad.wordpress.com/2014/03/17/mvc-secure-your-web-app/