【问题标题】:Setting up AAD Authentication in a Project with Autofac使用 Autofac 在项目中设置 AAD 身份验证
【发布时间】:2019-04-29 17:14:43
【问题描述】:

我有一个具有 AAD 身份验证的 Web API(在代码中,因为它在 IaaS 而不是 PaaS 中运行)它运行良好,但是如果我将 Autofac 配置添加到 Startup.cs,身份验证会中断,(如果我将 Autofac 放在 Auth 之后inizialization Autofac 中断)这让我认为配置正在相互覆盖。

我试图找到有关如何将它们一起使用的任何文档,但我无法找到任何信息。一个使用 HttpConfiguration,另一个使用 IAppBuilder,我不知道如何将它们组合在一起以使它们一起工作。

这是我的验证码:

public void ConfigureAuth(IAppBuilder app)
{
 app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
    app.UseCookieAuthentication(new CookieAuthenticationOptions());
    app.Map("/api", inner =>
    {
        inner.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions()
        {
            Tenant = tenant,
            TokenValidationParameters = new Tokens.TokenValidationParameters
            {
                ValidAudience = Audience
            }
        });
    });
}

这是 Autofac 代码

public static void Register(HttpConfiguration configuration)
{
   var builder = new ContainerBuilder();
   Bootstrapper.Configure(builder);
   var container = builder.Build();
   configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}

结合使用这两种工具的最佳做法是什么?

【问题讨论】:

  • 这里好像没有a Minimal, Complete, and Verifiable Example。例如,我们看不到您在哪里创建 HttpConfiguration 并将其设置在 IAppBuilder (example here) 中。 Autofac 和 AAD auth 没有特定的“最佳实践”——它可能不是 Autofac 特定的,而是你如何将它与任何 DI 容器连接起来。

标签: azure asp.net-web-api azure-active-directory autofac autofac-configuration


【解决方案1】:

我没有正确设置所有 WebAPI autofac 引用以获取我遵循的所有依赖项 this 快速入门,然后添加了我的引用。下面是新的 ConfigureAutofac 功能(配置身份验证保持不变)

private void ConfigureAutofac(IAppBuilder app)
{
    //Autofac info from https://autofaccn.readthedocs.io/en/latest/integration/webapi.html#quick-start
    var builder = new ContainerBuilder();

    // STANDARD WEB API SETUP:
    // Get your HttpConfiguration. In OWIN, you'll create one
    // rather than using GlobalConfiguration.
    var config = new HttpConfiguration();

    // Register your Web API controllers.
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //Register WebApi Controllers
    builder.RegisterType<AutofacManager>().As<IAutofacManager>();
    builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());

    var container = builder.Build();
    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container); //Set the WebApi DependencyResolver

    // and finally the standard Web API middleware.         
    app.UseAutofacMiddleware(container);
    app.UseAutofacWebApi(config);
    app.UseWebApi(config);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多