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

lit*_*est 5 dependency-injection asp.net-identity asp.net-core asp.net-core-webapi

我创建了一个使用Identity Server 4使用Bearer Token身份验证的Asp.Net Core 2.1 Web Api.我有两个db上下文,一个用于身份,另一个是我的自定义应用程序的数据访问.我希望能够在我的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();
    }
Run Code Online (Sandbox Code Playgroud)

控制器看起来像这样:

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

    public PlayerController(UserManager<ApplicationUser> _userManager)
    {
        userManager = _userManager;
    }
    .....
 }
Run Code Online (Sandbox Code Playgroud)

使用BaseApiController,如下所示:

[Route("api/[controller]")]
[Authorize]
public class BaseApiController : Controller
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

jer*_*oft 3

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);
    }
Run Code Online (Sandbox Code Playgroud)

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

services.AddIdentityCore<TUser>()
Run Code Online (Sandbox Code Playgroud)

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