I tried Googling a few things about custom attributes but I\'m still not sure how to go about it....
I\'m storing a few important details of the user in Session cook
You can create a custom AuthorizeAttribute and override AuthorizeCore() and HandleUnauthorizedRequest() as required. Add your own logic which will do the check and redirect if necessary.
I'm just showing a simple example using MVC's ActionFilterAttribute (which is not the best place to do authentication/authorization)
public class VerifyUserAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var user = filterContext.HttpContext.Session["UserID"];
if (user == null)
filterContext.Result = new RedirectResult(string.Format("/User/Login?targetUrl={0}",filterContext.HttpContext.Request.Url.AbsolutePath));
}
}
Do not forget to set the Session["UserID"] variable in your /User/Login action method after proper user validation.
You can create your own version of the Authorize attribute by implementing the IAuthorizationFilter interface. Here's an example:
class MyCustomFilter : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Session["UserID"] == null)
{
filterContext.Result = new RedirectResult("/");
}
}
}
and a usage example:
[MyCustomFilter]
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}