在Asp.Net Core 2中将SignInManager和AspNetUserManager注入中间件

时间:2018-03-19 09:30:39

标签: c# asp.net-core dependency-injection asp.net-core-middleware

我正在尝试将SignInManager<ApplicationUser>AspNetUserManager<ApplicationUser>注入我的WebApi的Refresh Token中间件。我不是在使用Identity,所以我的ApplicationUser类是

public class ApplicationUser : IdentityUser<int>, IEntity

在我的中间件构造函数中,我有;

private readonly AuthService _service;

public TokenProviderMiddleware(
    RequestDelegate next, 
    Func<IMyDataContext> context,
    SignInManager<ApplicationUser> signInManager,
    AspNetUserManager<ApplicationUser> userManager)
{
    _next = next;

    _serializerSettings = new JsonSerializerSettings
    {
        Formatting = Formatting.Indented
    };

    _service = new AuthService(context, signInManager, userManager);
}

在我的Startup.cs中我有以下内容;

public void ConfigureServices(IServiceCollection services)
{
        services.AddDbContext<MyDataContext>(
            options => options.UseSqlServer(DbGlobals.DevDatabase));

        services.AddTransient<IMyDataContext, MyDataContext>();
        services.AddTransient<Func<IMyDataContext>>(provider => () => provider.GetService<IMyDataContext>());

        services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddEntityFrameworkStores<BemfeitoDataContext>()
        .AddDefaultTokenProviders();

        services.Configure<IdentityOptions>(options =>
        {
            // Password settings
            options.Password.RequireDigit = true;
            options.Password.RequiredLength = 8;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = true;
            options.Password.RequireLowercase = false;
            options.Password.RequiredUniqueChars = 6;

            // Lockout settings
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
            options.Lockout.MaxFailedAccessAttempts = 10;
            options.Lockout.AllowedForNewUsers = true;

            // User settings
            options.User.RequireUniqueEmail = true;
        });

        // Configure JwtIssuerOptions
        services.Configure<JwtIssuerOptions>(options =>
        {
            options.Issuer = JwtSettings.Issuer;
            options.Audience = JwtSettings.Audience;
            options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
        });

        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = JwtSettings.Issuer,

            ValidateAudience = true,
            ValidAudience = JwtSettings.Audience,

            ValidateIssuerSigningKey = true,
            IssuerSigningKey = _signingKey,

            RequireExpirationTime = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };

        services.AddAuthentication(options =>
        {
             options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
             options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
         })
         .AddJwtBearer(configureOptions =>
         {
             configureOptions.ClaimsIssuer = JwtSettings.Issuer;
             configureOptions.TokenValidationParameters = tokenValidationParameters;
             configureOptions.SaveToken = true;
             configureOptions.Events = new JwtBearerEvents
             {
                 OnAuthenticationFailed = context =>
                 {
                     Console.WriteLine("OnAuthenticationFailed: " +
                        context.Exception.Message);
                        return Task.CompletedTask;
                 },
                 OnTokenValidated = context =>
                 {
                     Console.WriteLine("OnTokenValidated: " +
                        context.SecurityToken);
                        return Task.CompletedTask;
                 }
            };
        });

            // api user claim policy
            services.AddAuthorization(options =>
            {
                options.AddPolicy("ApiUser", policy => policy.RequireClaim(JwtClaimIdentifiers.Rol, JwtClaims.ApiAccess));
            });

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpErrorHandlerMiddleware();

            app.UseTokenProviderMiddleware();
            app.UseRefreshTokenProviderMiddleware();
            app.UseAuthentication();

            app.UseMvc();

        }

当我运行时,我收到以下错误;

  

InvalidOperationException:无法解析作用域服务&#39; Microsoft.AspNetCore.Identity.SignInManager`1 [ApplicationUser]&#39;来自root provider。

我尝试添加以下瞬态;

        services.AddTransient<IUserStore<ApplicationUser>, UserStore<ApplicationUser, ApplicationRole, MyDataContext, int>>();
        services.AddTransient<SignInManager<ApplicationUser>>();
        services.AddTransient<UserManager<ApplicationUser>>();

但是我似乎正在寻找注入依赖关系的兔子洞,因为它现在也要求注入UserStore?注入这些服务是否有更简单的方法?

1 个答案:

答案 0 :(得分:1)

也许可以使用一种更简单的方法来访问中间件中的这些服务。考虑以下方法,而不是尝试将SignInManager signInManager和AspNetUserManager userManager直接注入中间件,而是注入Microsoft.AspNetCore.Http.IHttpContextAccessor _httpContextAccessor

然后,您可以使用_httpContextAccessor来访问signInManager和userManager服务,如下所示:

var userManager = _httpContextAccessor.HttpContext.RequestServices.GetService<AspNetUserManager<ApplicationUser>>();
var signInManager = _httpContextAccessor.HttpContext.RequestServices.GetService<SignInManager<ApplicationUser>>();

还要确保您的中间件类具有以下using语句: using Microsoft.Extensions.DependencyInjection;