HandleUnauthorizedRequest not overriding - c#

In my asp.net mvc3 application, I have a custom Authorization Attribute as seen below.
public class CustomAuthorize : AuthorizeAttribute
{
public IAccountRepository AccountRepository { get; set; }
public CustomAuthorize()
{
this.AccountRepository = new UserModel();
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
base.AuthorizeCore(httpContext);
return AccountRepository.isEnabled(HttpContext.Current.User.Identity.Name);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
}
}
I have the [CustomAuthorize] tag on my controller actions, and the AuthorizeCore method works fine - it performs the logic I want it to (making sure the account is actually enabled), and then returning as such.
However, the overridden HandleUnauthorizedRequest method, which as I understand it should allow me to control the behaviour of an unauthorized request, is not running at all. I put a breakpoint there, I put code in there, I access my application unauthorized, and the code never runs.
What am I missing?
EDIT: I did some more research and found a few other people who had this problem, but no solution unfortunately.
EDIT2: Sample code
[CustomAuthorize]
public class UserController: Controller
{
public UserController()
{
//do stuff here
}
}
EDIT 3: #Fabio
Here's what I'm trying to do. I have a login page (forms auth) that works fine - it calls my custom login, and then calls my AuthorizeCore override. My application uses a large amount of ajax calls, and my eventual goal is for whenever a user is using the application, and the administrator disables them, making an ajax call after being disabled (though still being logged in) should log them out. However, in order to do this, i want to return a custom response if the user is making an ajax call, and for that, I need to ovverride HandleUnauthorizedRequest. But my Authorize Core (and by extension HandleUnauthorizedRequest) are being ignored if the user is logged in (despite the fact that I have customauthorize tags on all of my controller actions that the ajax is calling).
In short: I want to authorize the user on every request, not just the login request (which seems to be what the membership provider is doing right now)

I ended up changing my approach a fair bit. I implemented individual permissions checking, and then that caused AuthorizeCore to be called every time (and not be cached, which I guess was what was happening before).
Interestingly enough, putting a breakpoint on the HandleUnauthorizedRequest override still doesn't break, but putting it inside the method will. Strange, and threw me off for a bit, but I've solved it now.
Code if anyone is interested:
public class CustomAuthorize : AuthorizeAttribute
{
public string Permissions { get; set; }
private IAccountRepository AccountRepository { get; set; }
private string[] permArray { get; set; }
private string reqStatus { get; set; }
public CustomAuthorize()
{
this.AccountRepository = new UserModel();
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
base.AuthorizeCore(httpContext);
if (Permissions != null) {
permArray = Permissions.Trim().Split(' ');
if (AccountRepository.isEnabled(httpContext.User.Identity.Name)) {
this.reqStatus = "permission";
return AccountRepository.hasPermissions(permArray);
} else {
return false;
}
} else {
return AccountRepository.isEnabled(httpContext.User.Identity.Name);
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (this.reqStatus == "permission") {
filterContext.Result = new RedirectResult(MvcApplication.eM.cause("no_permission", "redirect"));
} else {
base.HandleUnauthorizedRequest(filterContext);
}
}
}
And then I decorated the controller with this:
[CustomAuthorize(Permissions="test_perm")]

This may be a stupid answer/question but is AccountRepository.isEnabled method returning false so that the HandleUnauthorizedRequest can be executed?
If it's returning true, then the HandleUnauthorizedRequest method won't be executed.

Related

Custom AuthorizeAttribute not being implemented

In our MVC solution we have two custom implementations of AuthorizeAttribute - one is named BasicHttpAuthorizeAttribute and has been used in production for years, and the other RoleAuthorizeAttribute, which was recently added.
When creating RoleAuthorizeAttribute I simply copied BasicHttpAuthorizeAttribute and modified some of the already-overridden methods.
Both attributes serve the purpose of authenticating the user, and the RoleAuthorizeAttribute of verifying that the user has the required role.
However, RoleAuthorizeAttribute never authenticates the user. It is simply not being called and instead our MVC controllers throw an exception when a non-logged-in user reaches the controller action and the code requests the context user.
Below is the outline for this custom AuthorizeAttribute. If I put breakpoints on all of those methods I find that none of them are hit when a request is made.
Can anyone explain why this class is not being used to authenticate users? Why is it that an unauthenticated user is not being redirected to the login page, but if I swap RoleAuthorize for BasicHttpAuthorize or simply the base Authorize then they are redirected?
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class RoleAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
/// <summary>
/// Gets or sets the <see cref="Role"/> enumerations required for authorization.
/// </summary>
public Role[] RequiredRoles
{
get {...}
set {...}
}
public bool RequireSsl { get; set; };
public bool RequireAuthentication { get; set; }
public RoleAuthorizeAttribute(params Role[] requiredRoles)
{
// ...
}
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
// ...
}
protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
// ...
}
private bool Authenticate(System.Web.Http.Controllers.HttpActionContext actionContext)
{
// ...
}
public static bool TryGetPrincipal(string authHeader, out IPrincipal principal)
{
// ...
}
public static bool TryGetAuthCookie(out IPrincipal principal)
{
// ...
}
private static string[] ParseAuthHeader(string authHeader)
{
// ...
}
private static bool TryGetPrincipal(string username, string password, out IPrincipal principal)
{
// ...
}
}
And here is an example of its usage:
namespace MyProject.Areas.Customer.Controllers
{
[RoleAuthorize(Role.Customer, Role.CompanyAdmin)]
public partial class OrderController : MyCustomController
{
private static readonly ILog Log = LogManager.GetLogger(typeof (OrderController));
public ActionResult Index(int id)
{
// ...
}
}
}
We use Basic Authentication so there's a header set thus:
I've seen older questions asking about the same problem, but in those cases, they also override an AuthorizeCore method which no longer seems to be present on the AuthorizeAttribute class.
I figured out myself why this was happening.
There are two AuthorizeAttributes - one in the System.Web.Http namespace and the other in System.Web.Mvc. I wasn't aware of this and was trying to build a one-size-fits-all attribute, so my attribute was working for WebAPI requests but not for MVC controller requests.
The difference in these two attributes is in the OnAuthorize method where they each take a different context argument.
Once I had built two separate attributes (which are almost identical), each deriving from a different AuthorizeAttribute, everything worked as expected.

OnActionExecuting Not Getting Executed

I am troubleshooting a ASP.NET MVC application and on one server the OnActionExecuting is not firing. It has been a long time since I looked at filters. What can keep the OnActionExecuting from running? The effect in our application is the user context never really gets set up (Initialize)... so everything redirects the user back to the login page.
Here is the code of the filter. Note "Jupiter" was the codename of the project
public class JupiterAuthenticationFilter : IActionFilter
{
private readonly IJupiterContext _jupiterContext;
public JupiterAuthenticationFilter(IJupiterContext jupiterContext)
{
if (jupiterContext == null)
{
throw new ArgumentNullException("jupiterContext");
}
_jupiterContext = jupiterContext;
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
_jupiterContext.Initialize();
}
public void OnActionExecuted(ActionExecutedContext filterContext)
{
}
}
It can happen when your Controller has System.Web.MVC implementation, but ActionFilter has System.Web.Http.

Overriding AuthorizeCore from AuthorizeAttribute is not being invoked

For some reason, only the method OnAuthorization is being invoked, but AuthorizeCore not.
this is how I call it:
[AuthorizeWithRoles(Roles = "Affiliate")]
public string TestOnlyAffiliate()
{
return "ok";
}
this is the actual attribute.
public class AuthorizeWithRolesAttribute : AuthorizeAttribute
{
public string Roles { get; set; }
//
//AuthorizeCore - NOT INVOKING!
//
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return true;
}
public void OnAuthorization(AuthorizationContext filterContext)
{
}
}
You're not supposed to override OnAuthorization. It deals with potential caching issues and calls AuthorizeCore.
http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/1acb241299a8#src/System.Web.Mvc/AuthorizeAttribute.cs
// In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later be served the
// cached page.
Put your custom logic in AuthorizationCore.
Not sure if this helps you at all, but I ran into this same thing and determined that, at least for my purposes, I didn't need to override AuthorizeCore at all. I'm not sure why it's there, to be honest. As MSDN says, OnAuthorization is invoked "when a process requests authorization." This means that it will be invoked for any method that has your AuthorizeWithRoles attribute. You can put your custom code within OnAuthorization to check whether or not the user has permission, and since you can get the httpContext from filterContext, there's really no need for AuthorizeCore. Here's a simple example that works for me:
public class LoginRequired : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (Common.ValidateCurrentSession(filterContext.HttpContext))
{
//this is valid; keep going
return;
}
else
{
//this is not valid; redirect
filterContext.Result = new RedirectResult("/login");
}
}
}
I hope that helps. Besides that, obviously you'll need to declare that OnAuthorization is an override.
EDIT: I believe the base OnAuthorization method is what calls into AuthorizeCore. Since you're overriding OnAuthorization, obviously that call is lost. I believe overriding AuthorizeCore would only be relevant if you left OnAuthorization alone or if you called base.OnAuthorization(filterContext) within the overridden method.

Authorization and authentication in MVC application

Authorization and authentication in MVC application
I have an internal web app developed in C# using MVC 2. I want to use AD roles/groups to do authorization. Thus I have 3 access group Admin, Basic, Readonly. The access to the application will be controlled through these groups.
Now when I hit an action/page of my MVC app, the requirements are:
1) Check level of access (is in either group Admin, Basic or Readonly)
2) If in a group - serve the page.
If not - serve the 401 Unauthorized page.
I am probably confusing myself with the concepts authorization/authentication, but this is how it is set up so far (from answers, google and my own efforts flowing from this question:
public static class AuthorizationModule
{
public static bool Authorize(HttpContext httpContext, string roles)
{
...
//Check Configuration.AppSettings for the roles to check
//using httpContext.User check .IsInRole for each role and return true if they are
...
//other wise throw new HttpException(401,.....)
}
...
}
public class AuthorizeByConfigurationAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//Essentially at the moment this is pretty much the same as AuthorizationModule.Authorize(HttpContext httpContext, string roles)
}
}
//This code from http://paulallen.com.jm/blog/aspnet-mvc-redirect-unauthorized-access-page-401-page
public class RequiresAuthenticationAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new ViewResult {ViewName = "AccessDenied"};
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
The problems with this are that I seem to need to decorate my action methods twice now, ala:
[AuthorizeByConfiguration(Roles = "Admin, Basic, Readonly")]
[RequiresAuthentication(Roles = "Admin, Basic, Readonly")]
public ActionResult Index(string msg)
{
...
}
And the next problem is that it seems I have three separate methods all trying to do the same thing. I am overriding methods based on advice and not entirely sure how they were meant to work originally. How could I go about implementing my requirements?
edit: Since this is an IntrAnet app, all users who sign on with their network accounts will be able to access this app. I need to restrict the access so that only those who belong to certain Active Directory security groups can access this app
I have wrapped all the methods concerning auth with the interface IAuthorization.
Here is an example custom attrbiute you would need to add the Roles property and your own implementaion.
Attribute calls the filter itself for testability reasons.
public class SomeAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
var filter = new SomeAuthorizeFilter(DependencyLookup.Resolve<IAuthorization>());
filter.OnAuthorization(filterContext);
}
}
public class SomeAuthorizeFilter : IAuthorizationFilter
{
private readonly IAuthorization _authorization;
public SomeAuthorizeFilter(IAuthorization authorization)
{
_authorization = authorization;
}
protected virtual ActionResult ResultWhenNotAuthenticated(AuthorizationContext filterContext)
{
//snip..
//default
RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary
{
{"action", "Index"},
{"controller", "Home"}
};
return new RedirectToRouteResult(redirectTargetDictionary);
}
#region IAuthorizationFilter Members
public void OnAuthorization(AuthorizationContext filterContext)
{
if (!_authorization.GetCurrentUserIdentity().IsAuthenticated)
{
filterContext.Result = ResultWhenNotAuthenticated(filterContext);
}
}
#endregion
}

Active Directory Authentication on ASP.NET MVC

I have a couple of table on my database that specify witch users ( Depending on your AD Username) can actually use the current ASP.NET MVC 2 app I'm building.
My question is how ( or more likely where and where do I put it? On the master page?? ) do i write a method that gets the AD user out of the HTTP context and validates it against the database to see if you can actually use the app? If you can... the idea it's to write a couple of keys in the Session object with the information I need ( Role, Full Name, etc ).
I'm quite confused regarding how I should accomplish this and if it's actually the right way... Keep in mind that I have an admin section and non-admin section in my app.
Any thoughts?
Edit: Keep in mind that I do not care to authenticate the user through a form. All I want to check is if according to my database and your AD username you can use my app. If you can write to session in order to perish the information I need. Otherwise just throw an error page.
This is what I've implemented so far, is this the way to go?
What's the second method for? ( I'm sorry I'm kind of new to c#) What I want to do it's actually throw a view if yo're not authorized...
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized)
{
var canUse = this._userRepo.CanUserUseApp(httpContext.User.Identity.Name);
if (!canUse)
{
isAuthorized = false;
}
}
return isAuthorized;
}
You could activate and use Windows (NTLM) authentication and then write a custom [Authorize] attribute where you could fetch the currently connected AD user and perform the additional check of whether he is authorized or not to use the application against your data store. Then you would decorate controllers/actions that require authorization with this custom attribute.
UPDATE:
Here's an example of how such custom attribute might look like:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized)
{
// The user is authorized so far => check his credentials against
// the custom data store
return IsUserAllowedAccess(httpContext.User.Identity.Name);
}
return isAuthorized;
}
private bool IsUserAllowedAccess(string username)
{
throw new NotImplementedException();
}
}
and then:
[MyAuthorize]
public class FooController: Controller
{
public ActionResult Index()
{
...
}
}
Create a class called AdminAttribute with this code
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AdminsAttribute : AuthorizeAttribute
{
public AdminsAttribute()
{
this.Roles = "MSH\\GRP_Level1,MSH\\Grp_Level2";
}
}
public class HomeController : Controller
{
[Admins]
public ActionResult Level1()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}

Categories