如何通过AspNet.Core 2.1中的依赖注入添加UserManager?

时间:2018-07-22 14:17:14

标签: asp.net-core dependency-injection asp.net-identity asp.net-core-webapi

我已经创建了一个使用Identity Server 4使用Bearer Token身份验证的Asp.Net Core 2.1 Web Api。我有两个数据库上下文,一个用于身份验证,一个用于我的自定义应用程序的数据访问。我希望能够通过控制器中的依赖项注入在Web Api中使用UserManager和UserStore。

问题在于,一旦我添加了DI的“相关”代码,我的控制器方法就会抛出302并试图将我重定向到登录URL。就像我的承载身份验证已被覆盖。下面是我的Startup.cs的样子。关于应该如何做的任何想法?

   public void ConfigureServices(IServiceCollection services)
   {

        string connectionString = Configuration.GetConnectionString("DefaultConnection");
        var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

        services.AddDbContext<CustomContext>(options =>
            options.UseSqlServer(connectionString));

        // start of the stuff that should add the usermanager and userstore
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(connectionString));


        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
        // end of the stuff

        services.AddMvcCore()
            .AddAuthorization()
            .AddJsonFormatters();

        services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "http://authenticate.com";
                options.RequireHttpsMetadata = false;

                options.ApiName = "api1";
            });

        services.AddCors(options =>
        {
            // this defines a CORS policy called "default"
            options.AddPolicy("default", policy =>
            {
                policy.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
            });
        });


    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseAuthentication();
        app.UseCors("default");
        app.UseMvc();
    }

控制器看起来像这样:

public class PlayerController : BaseApiController
{
    private readonly UserManager<ApplicationUser> userManager;

    public PlayerController(UserManager<ApplicationUser> _userManager)
    {
        userManager = _userManager;
    }
    .....
 }

使用这样的BaseApiController:

[Route("api/[controller]")]
[Authorize]
public class BaseApiController : Controller
{
    ...
}

1 个答案:

答案 0 :(得分:0)

services.AddIdentity<TUser>() 添加了“不必要的”身份验证配置,因为您已经拥有 services.AddAuthentication("Bearer").AddIdentityServerAuthentication() 配置中的承载方案。看看下面的 AddIdentity() 代码。请注意还添加了多少方案(包括 cookie 方案)。

public static IdentityBuilder AddIdentity<TUser, TRole>(
        this IServiceCollection services,
        Action<IdentityOptions> setupAction)
        where TUser : class
        where TRole : class
    {
        // Services used by identity
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
            options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
            options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
        })
        .AddCookie(IdentityConstants.ApplicationScheme, o =>
        {
            o.LoginPath = new PathString("/Account/Login");
            o.Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync
            };
        })
        .AddCookie(IdentityConstants.ExternalScheme, o =>
        {
            o.Cookie.Name = IdentityConstants.ExternalScheme;
            o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
        })
        .AddCookie(IdentityConstants.TwoFactorRememberMeScheme, o =>
        {
            o.Cookie.Name = IdentityConstants.TwoFactorRememberMeScheme;
            o.Events = new CookieAuthenticationEvents
            {
                OnValidatePrincipal = SecurityStampValidator.ValidateAsync<ITwoFactorSecurityStampValidator>
            };
        })
        .AddCookie(IdentityConstants.TwoFactorUserIdScheme, o =>
        {
            o.Cookie.Name = IdentityConstants.TwoFactorUserIdScheme;
            o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
        });

        // cut for brevity

        return new IdentityBuilder(typeof(TUser), typeof(TRole), services);
    }

你不需要那个。你需要的是:

services.AddIdentityCore<TUser>()

不添加其他身份验证配置。