Question

I have a .net WebApi2 Project. I am using IIS which provides basic authentication.

There are 2 clients that need access to this web service and there are 2 controllers. Controller #1 = EmployeeController and Controller #2 = InvoiceController I have a database that list usernames and roles. Role1 = EmployeeUsers and Role2 = InvoiceUsers.

I would like to use the Authroize attribute as such...

[Authorize(Roles = "EmployeeUsers ")]
public class EmployeeController : ApiController
{

}

and

[Authorize(Roles = "InvoiceUsers")]
public class InvoiceController : ApiController
{

}

Without the Authorize Attribute I can get to the authenticated user via Request.GetRequestContext().Principal but I can only get to that after the user is authenticated and allowed access to the controller.

I want to be able to get the Basic Authenticated User Information (Remember, IIS is handling the basic authentication) and use the [Authorize] attribute to allow access to a controller based on certain roles that user may be in... but at what point can I get access to the authenticated user (Principal), check his role, and allow the [Authorize] attribute to do its work or allowing or denying access to certain controllers?

FYI... IIS has to be used to handle the basic authentication... so basic authentication is set in IIS and my web.config has authentication mode="Windows" set.

How can I use the Authorize attribute to limit access to a controller based on a user authenticated via IIS?

Was it helpful?

Solution

I don't have much experience with using IIS for authentication, but you can create your own attribute that inherits from AuthorizeAttribute, so you can roll your own with something like this:

public class MyAuthorizationAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var principal = actionContext.Request.GetRequestContext().Principal;
            if (!principal.IsInRole(this.Roles))
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            }
        }
    }

Then you'd decorate your controller with [MyAuthorizationAttribute(Roles = "Foo")]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top