使用Autofac在项目中设置AAD身份验证

时间:2019-04-29 17:14:43

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

我有一个具有AAD身份验证的Web API(在代码中,因为它在IaaS而非PaaS中运行)效果很好,但是如果我将Autofac配置添加到Startup.cs,则身份验证会中断,(如果我将Autofac放在Auth之后初始化(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);
}

同时使用这两个工具的最佳实践是什么?

1 个答案:

答案 0 :(得分:0)

我没有正确设置所有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);
}