ASP.NET MVC Authentication links


ASP.NET MVC Authentication links

Published on Sun 16 Dec 2007 12:12 ( 2 years, 8 months ago)
ASP.NET Learning notes

Some links on learning ASP.NET MVC:

http://weblogs.asp.net/fredriknormen/archive/2007/11/25/asp-net-mvc-framework-security.aspx

[ControllerAction]
public void Edit(int? id)
{
if (!Roles.IsUserInRole("Admin"))
throw new SecurityException("Access denied");
  ...
}

To avoid writing this check in the Action methods we can instead use the PrincipalPermissionAttributes shipped with .Net:

[ControllerAction]
[PrincipalPermission(SecurityAction.Demand, Role="Admin"]
public void Edit(int? id)
{
   ...
}

If we want to make sure all Action methods in a Controller have the check, we can add the PrincipalPermissionAttribute to the Controller class:

[PrincipalPermission(SecurityAction.Demand, Role="Admin")]
public class HomeController : Controller

If we want to handle the SecurityException we can use the ExceptionHandlerAttribute I wrote about in my previous post. This can catch the SecurityException and Render a View that will display the exception message.

[ControllerAction]
[PrincipalPermission(SecurityAction.Demand, Role="Admin"]
[ExceptionHandler("Error", typeof(SecurityException))]
public void Edit(int? id)
{
   ...
}

If we don’t want to use the PrincipalPermissionAttribute and instead write our own Security handler, we can override the OnPreAction method and implement the security check. The OnPreAction method will be executed before any Action methods are executed.

protected override void OnPreAction(string actionName, System.Reflection.MethodInfo methodInfo)
{
if (actionName == "Edit")
   {
if (!Roles.IsUserInRole("Admin") || !User.Identity.IsAuthenticated || !User.Identity.Name = "Administrator")
throw SecurityException("Access denied!");
   }
}

http://forums.asp.net/t/1192300.aspx

You could always make a base controller and have your other controllers you want to secure extend it.

Example

public class SecureController : Controller

{

    public SecureController()

    {

        HttpContext context = HttpContext.Current;

        if (context.User == null || !context.User.Identity.IsAuthenticated)

        {

            // redirect to login.

      } 

    }

}

public class MemberController : SecureController

{

}


Related posts:


Search related in web:

Custom Search

RSS Feed

One click subscribe this blog in your google reader!

Be social!


Want to say something here? please sign in



Blog posts link to this page
What are friends tweeting?
Tags cloud
Monthly Archives