【问题标题】:ASP.NET MVC Authenticate before controller instantiatedASP.NET MVC 在控制器实例化之前进行身份验证
【发布时间】:2015-01-29 20:04:16
【问题描述】:

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

发生的情况是,在评估 [Authorize] 属性和验证用户身份之前,控制器正在被实例化。这会强制 Unity 在用户登录之前执行依赖注入并使用有关用户的信息。当我们使用集成 Windows 身份验证时,这都不是问题,但现在我们使用 OpenID Connect to Azure AD 并且用户信息不是t 在那里,直到他们登录(这发生在控制器启动之后)。

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

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

控制器:

[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);
                }
            }
        });
}

【问题讨论】:

  • 我也被这个绊倒了,虽然没有任何 DI 的东西。在基本控制器的构造函数中需要一个 userId,并且惊讶地看到构造函数在 AuthorizedAttribute 移动用户之前被调用。
  • 解释为什么会这样stackoverflow.com/a/4462767/10245

标签: c# asp.net-mvc authentication openid owin


【解决方案1】:

在网上找不到专门解决我的问题的任何内容后,我决定深入研究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...),并且在用户登录之前没有解决任何依赖关系在。

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


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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    相关资源
    最近更新 更多