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

我们两清 提交于 2021-02-08 13:56:19

问题


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?


回答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



来源:https://stackoverflow.com/questions/46027896/how-can-i-use-windows-authentication-in-mvc-but-use-the-newer-identity-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!