ASP.NET MVC Authentication links
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 : ControllerIf 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:
- To "refresh" a SqlDataSource.
- asp:ControlParameter vs asp:FormParameter
- output a line in a batch *without* crlf
- Write code with no getters???
- Dump SQL Server Express' DB Schema
- My suggestions on Web2py's route design
- Good comparing of GAE Data Store .vs. Amazon Simple DB .vs. MS SSDS
- Very good articles on MVC, MVP and more.
- Presenter First approach in MVP
- ASP.NET MVC Preview 3 just released
Search related in web: