Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 920
user1189352 Avatar asked Oct 03 '15 17:10

user1189352


People also ask

What is Authorize filter in MVC?

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.


2 Answers

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.

like image 186
Arghya C Avatar answered Oct 17 '22 01:10

Arghya C


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();
}
like image 27
Nasreddine Avatar answered Oct 17 '22 02:10

Nasreddine