asp.net-core - 如何在 AspNet.Core 2.1 中通过依赖注入(inject)添加 UserManager?

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

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

问题是,一旦我添加了 DI 的“相关”代码,我的 Controller 方法就会抛出 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();
    }

Controller 如下所示:
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
{
    ...
}

最佳答案

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>()
它不会添加另一个身份验证配置。

关于asp.net-core - 如何在 AspNet.Core 2.1 中通过依赖注入(inject)添加 UserManager?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51465992/

相关文章:

c# - 可移植类库的 IoC 容器

c# - 将 asp.net MVC 从 5.0.0-beta2 更新到 5.0.0-rc1

asp.net-core - ASP.NET Core 3.0 - 身份 UI 管理文件夹未接收布局

asp.net - asp Identity 2.0 添加新角色并将用户添加到角色

asp.net-web-api - 字符串类型不能构造

c# - ASP.NET Core JWT 身份验证更改 Claims(子)

asp.net-core - MVC 6 中 'Session_Start' 的替代方案

c# - 是否可以在不使用 FromQuery 的情况下在 Swagger UI 中为输入模型属性赋予不同的名称?

Symfony2 : How to access a service inside an extension's load() method?

c# - EntityFramework 代码首先是 : Set order of fields