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 cookies (ex UserID) once the user log's in.. and all I want to do is create an attribute where if the
if (Session["UserID"] == null)
then it will redirect to login just like the [Authorize] attribute does. That way I can apply this attribute on the Controller level everywhere.
Should I overwrite the Authorize attribute? Create a new one? How do I get it to redirect to login as well?
I'm also using ASP.NET MVC 4
Thanks for any help
Authorization filters allow you to perform authorization tasks for an authenticated user. A good example is Role based authorization. ASP.NET MVC 4 also introduced a built-in AllowAnonymous attribute. This attribute allows anonymous users to access certain Controllers/Actions.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With