ASP.NET MVC 在控制器实例化之前进行身份验证

ASP.NET MVC Authenticate before controller instantiated

我有一个控制器,我在其中将服务接口注入到构造函数中。 该服务也将接口注入到其构造函数中。 IoC 容器 (Unity) 在为给定接口构造 returns 的 class 之一时需要使用有关用户的信息。

正在发生的事情是,在评估 [Authorize] 属性和验证用户之前实例化控制器。这会强制 Unity 在用户登录之前执行依赖注入并使用有关用户的信息。None 当我们使用集成 windows 身份验证时,这是一个问题,但现在我们使用 OpenID Connect 来Azure AD 和用户信息在他们登录之前不存在(这发生在控制器初始化之后)。

我听说(在其他帖子中)有一种方法可以配置我的 owin 启动 class 以在此过程中更早地移动身份验证,但我找不到有关如何执行此操作的任何示例。我需要在实例化控制器之前进行身份验证。

这是我所拥有的一个简化示例...

控制器:

[Authorize]
public class MyController : Controller
{
    private readonly IMyService myService;

    public MyController(IMyService myService)
    {
        this.myService = myService;
    }

    // ...
}

统一配置:

public class UnityBootstrap : IUnityBootstrap
{
    public IUnityContainer Configure(IUnityContainer container)
    {
        // ...

        return container
            .RegisterType<ISomeClass, SomeClass>()
            .RegisterType<IMyService>(new InjectionFactory(c =>
            {
                // gather info about the user here
                // e.g.
                var currentUser = c.Resolve<IPrincipal>();
                var staff = c.Resolve<IStaffRepository>().GetBySamAccountName(currentUser.Identity.Name);
                return new MyService(staff);
            }));
    }
}

OWIN 启动(Startup.Auth.cs):

public void ConfigureAuth(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions());

    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            ClientId = this.clientID,
            Authority = this.authority,
            PostLogoutRedirectUri = this.postLogoutRedirectUri,
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                RedirectToIdentityProvider = context =>
                {
                    context.ProtocolMessage.DomainHint = this.domainHint;
                    return Task.FromResult(0);
                },
                AuthorizationCodeReceived = context =>
                {
                    var code = context.Code;

                    var credential = new ClientCredential(this.clientID, this.appKey.Key);
                    var userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                    var authContext = new AuthenticationContext(this.authority, new NaiveSessionCache(userObjectID));
                    var result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, this.graphUrl);
                    AzureAdGraphAuthenticationHelper.Token = result.AccessToken;
                    return Task.FromResult(0);
                }
            }
        });
}

在网上找不到任何专门解决我的问题的内容后,我决定深入研究 ASP.NET MVC 5 application lifecycle。我发现我可以创建自定义 IControllerFactory(或从 DefaultControllerFactory 继承),我可以在其中定义 CreateController 方法。

在 CreateController 期间,我检查用户是否已通过身份验证。如果是,我只需让 DefaultControllerFactory 像往常一样创建控制器。

如果用户未通过身份验证,我将创建我的(非常)简单的 "Auth" 控制器,而不是请求的控制器(具有多层依赖关系的控制器),并且 RequestContext 保持不变。

Auth 控制器将毫无问题地实例化,因为它没有依赖项。注意:不会在 Auth 控制器上执行任何操作。一旦创建了 Auth 控制器,全局 AuthorizeAttribute 就会启动,用户将被引导进行身份验证(通过 OpenID 连接到 Azure AD 和 ADFS)。

登录后,他们被重定向回我的应用程序,原始 RequestContext 仍然完好无损。 CusomControllerFactory 将用户视为已通过身份验证并创建请求的控制器。

这个方法对我很有效,因为我的控制器有一个很大的依赖链被注入(即控制器依赖于 ISomeService,它依赖于许多 ISomeRepository、ISomeHelper、ISomethingEles...)并且 none 的依赖是解决,直到用户登录。

我仍然绝对愿意听取其他(更优雅的)关于如何实现我在最初问题中提出的问题的想法。


CustomControllerFactory.cs

public class CustomControllerFactory : DefaultControllerFactory
{
    public override IController CreateController(RequestContext requestContext, string controllerName)
    {
        var user = HttpContext.Current.User;
        if (user.Identity.IsAuthenticated)
        {
            return base.CreateController(requestContext, controllerName);
        }

        var routeValues = requestContext.RouteData.Values;
        routeValues["action"] = "PreAuth";
        return base.CreateController(requestContext, "Auth");
    }
}

Global.asax.cs

public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        // ...
        ControllerBuilder.Current.SetControllerFactory(typeof(CustomControllerFactory));
    }

    // ...
}

AuthController.cs

public class AuthController : Controller
{
    public ActionResult PreAuth()
    {
        return null;
    }
}