How can I use Windows authentication in MVC but use the newer identity database tables for role storage?

How can I use Windows authentication in MVC but use the newer identity database tables for role storage?

I'm using MVC 5 and Windows authentication, and need to use role management in a database, not AD groups. I've used the asp.net membership solution to do this in the past but would prefer to use the more modern identity table(s). I do not have access to AD groups. How can this be done?

Solutions/Answers:

Answer 1:

Personally I would skip the ASP.NET Identity part and just do it using a custom Authorization filter.

Historically the lines between Authentication (Can you prove who you are) and Authorization (What are you allowed to do) have been quite blurred in MVC.

When you have Windows authentication enabled, the Authentication part is taken care of, and the users’ identity in the form of Domain\Username is already set against the HttpContext. What you need to do is figure out what they are Authorized for.

The question is tagged as Oracle, and you may wish to use caching or something similar, so the exact method will vary. For simplicity we will assume that you have a static UserManager.IsInRole class / method that takes a Domain\Username and a comma separated Roles string to check and returns a bool indicating if the user is in one of the allowed roles. In practice you may need to mess about with Dependency Injection which can be a bit tricky with filters.

public class DbAuthorize : System.Web.Http.AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        var isAuthorized = base.IsAuthorized(actionContext);

        var user = actionContext.ControllerContext.RequestContext.Principal.Identity;

        if (user == null)
            return false;

        return isAuthorized && UserManager.IsInRole(user.Name, this.Roles);
    }
}

This can then be used in place of the standard Authorize attribute on Controllers or Actions of your Choice

Our Awesome Free Tools

References