How to create a custom attribute that will redirect to Login if it returns false, similar to the Authorize attribute – ASP.NET MVC

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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();
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x