Overriding AuthorizeAttribute in MVC 4
16,831
public class MyAuthorizeAttribute: AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
// The user is not authorized => no need to go any further
return false;
}
// We have an authenticated user, let's get his username
string authenticatedUser = httpContext.User.Identity.Name;
// and check if he has completed his profile
if (!this.IsProfileCompleted(authenticatedUser))
{
// we store some key into the current HttpContext so that
// the HandleUnauthorizedRequest method would know whether it
// should redirect to the Login or CompleteProfile page
httpContext.Items["redirectToCompleteProfile"] = true;
return false;
}
return true;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Items.Contains("redirectToCompleteProfile"))
{
var routeValues = new RouteValueDictionary(new
{
controller = "someController",
action = "someAction",
});
filterContext.Result = new RedirectToRouteResult(routeValues);
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
private bool IsProfileCompleted(string user)
{
// You know what to do here => go hit your database to verify if the
// current user has already completed his profile by checking
// the corresponding field
throw new NotImplementedException();
}
}
and then you could decorate your controller actions with this custom attribute:
[MyAuthorize]
public ActionResult FooBar()
{
...
}
Related videos on Youtube
Author by
Mukesh Sharma
while(true){ learn(); apply(); help(); } #SOReadyToHelp #NodeJs #Golang
Updated on September 23, 2022Comments
-
Mukesh Sharma over 1 year
In my application, I want to redirect the authorized user to update their profile page until they have provided required information. If they update profile, then the
IsProfileCompleted
is set to 'true' in the database.So, I knows that this can be done by putting check condition in required action of controller. But I want to do this by customizing the
AuthorizeAttribute
.I Googled and 'StackOverflowed' for information, but got confused. Please guide me.
-
iamraviraj over 8 yearsI am using this example for custom authorize in my mvc app. but, it doesn't redirect it to return url. Did I missed something?
-
iamraviraj over 8 yearsOnce again I am here,above issue has been resolved. I am using session based login and sometime it executes code that should be executed after authorization. I am using static properties for session keys. Can you help me with this? protected override bool AuthorizeCore(HttpContextBase httpContext) { if (string.IsNullOrEmpty(CurrentUser.UserName) || CurrentUser.UserName == " ") return false; return true; }
-
radbyx about 8 yearsIs this answer compatible with MVC 5 or should we make any changes?