Update . I recently came across this and figured out how to use AuthorizeAttribute to accomplish exactly what you need. My attribute, which checks if the user is an administrator, works as follows:
public class AuthorizeAdminAttribute : AuthorizeAttribute { public bool IsValidUser { get; protected set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); }
Essentially, the user must AuthorizeCore() determine if the user is logged in, save this result, and then authorize the roles on your system. Then in your HandleUnauthorizedRequest you need to find out if the request was unauthorized because the user was not registered or was caused because they were not authorized.
Old answer I use the
Authorize attribute, subclassing the
AuthorizeAttribute class. For example:
public class MyCustomAuthorizeAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); }
Now, when the controller or action is called and [MyCustomAuthorize] decorated, it will run this code to determine if the user is allowed based on your user logic, and if it will not redirect them exactly as the [Authorize] attribute will be.
I donβt know if this is the best approach, but this is what I came up with.
source share