首页 > 解决方案 > 在 AspNetCore Mvc 中使用依赖注入配置 CookieAuthenticationOptions

问题描述

有没有办法使用依赖注入来配置 cookie 身份验证选项?我想从数据库中获取一些设置,但此时我无权访问 DatabaseContext。

public void ConfigureServices(IServiceCollection services)
{
  ...
  services
            .AddAuthentication(Authentication.scheme)
            .AddCookie(Authentication.scheme, options =>
            {
                options.ExpireTimeSpan = new TimeSpan(30, 0, 0, 0, 0);
                options.Cookie.IsEssential = true;
                options.Cookie.Name = ".AUTH-Cookie";
                options.ReturnUrlParameter = "returnUrl";
                options.LoginPath = "/Security/SignIn";
                options.LogoutPath = "/Security/SignOut";
                options.EventsType = typeof(CookieAuthenticationEvents);
            });
  ...
}

我可以使用 AddOptions() 和 Configure() 对 ConfigureServices 中的其他项目执行此操作,但我无法弄清楚如何使用 CookieAuthenticationOptions...

services
  .AddOptions<MvcOptions>()
  .Configure<IDisplayMetadataProvider>((options, localizationMetadataProvider) =>
  {
    options.ModelMetadataDetailsProviders.Add(localizationMetadataProvider);
  });

我试图用 CookieAuthenticationOptions 做同样的事情,但它似乎并没有以同样的方式工作......

标签: asp.net-mvcasp.net-coredependency-injection

解决方案


关于如何在 cookie 身份验证选项中从数据库中获取数据,这里有一个简单的示例:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("YourConnnectionString")));

    var sp = services.BuildServiceProvider();
    var myDbContext = sp.GetService<MyDbContext>();
    var data = GetData(myDbContext);

    services.AddAuthentication(Authentication.scheme)
    .AddCookie(Authentication.scheme,options =>
    {
        options.LoginPath = data;
        //...
    });         
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{        
    //be sure you have added authentication middleware
    app.UseAuthentication();

    //if you use asp.net core 3.x,also need to add this
    //app.UseAuthorization();

}
public static string GetData(MyDbContext _context)
{
    //get the data from database
    var data = _context.Tables.Select(j => j.Loginpath).FirstOrDefault();
    return data;
}

推荐阅读