我有一个WebAPI应用,正在使用第三方身份验证器(Firebase身份验证)。
我可以进行身份验证,但是一旦用户登录到我的服务器,我想将凭据和用户数据保存到我的ASP.NET Identity表中。
如果我在Startup.cs文件中调用此行,我似乎可以使用UserManager创建帐户
services.AddIdentityCore<ApplicationUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
这允许我在构造函数中添加UserManager而不添加所有登录页面和如果我调用AddIdentity()通常会获得的默认cookie身份验证方案
但是,当我像这样在构造函数中添加SignInManager时
public ValuesController(SignInManager<ApplicationUser> signInManager)
我似乎仍然收到此错误。
执行请求时发生未处理的异常。 System.InvalidOperationException:无法解析类型的服务 'Microsoft.AspNetCore.Identity.SignInManager`1 [mvcWithAuth.Data.ApplicationUser]' 尝试激活时 “ testWebAPIFB.Controllers.ValuesController”。
这似乎意味着AddIdentityCore没有添加SignInManager。如何将SignInManager添加为要依赖项注入的类?
答案 0 :(得分:1)
您应使用 AddIdentity ,因为SignInManager未在DI容器中注册
喜欢
services.AddIdentity<ApplicationUser>()
.AddEntityFrameworkStores<ApplicationDbContext>()
或
注册SignInManager
services.TryAddScoped<SignInManager<ApplicationUser>>();
答案 1 :(得分:0)
SignInManager由AddIdentity
注册。 AddIdentityCore
仅注册UserManger。
在您的代码使用中,
services.AddIdentity<ApplicationUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
编辑:将JWTBearer设置为默认的身份验证方案,这就是我所做的
services.AddDbContext<ApplicationDbContext>(/*options => Db Config*/);
services.AddIdentity<ApplicationUser>(cfg =>
{
cfg.Password.RequireDigit = true;
cfg.Password.RequiredLength = 8;
cfg.Password.RequireNonAlphanumeric = false;
cfg.Password.RequireUppercase = false;
cfg.Password.RequireLowercase = true;
cfg.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication(cfg =>
{
cfg.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
cfg.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = Configuration["Tokens:Issuer"],
ValidAudience = Configuration["Tokens:Issuer"],
IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
};
});
答案 2 :(得分:0)
这似乎意味着AddIdentityCore没有添加SignInManager。
是的。如果检查Addidentity和AddIdentityCore的源代码,您会发现AddIdentityCore
仅注册UserManager
而没有SignInManager
>
要将SignInManager
与AddIdentityCore
添加,可以尝试:
IdentityBuilder builder = services.AddIdentityCore<ApplicationUser>();
builder = new IdentityBuilder(builder.UserType, builder.Services);
builder.AddEntityFrameworkStores<ApplicationDbContext>();
builder.AddSignInManager<SignInManager<ApplicationUser>>();
请参阅.Net Core 2.0 Web API using JWT - Adding Identity breaks the JWT authentication
答案 3 :(得分:0)
使用此代码对您有用。
在您的控制器中
private readonly SignInManager<User> _signInManager;
public SomeController(
SignInManager<User> signInManager)
{
_signInManager = signInManager;
}
在您的Startup.cs中
services
.AddIdentity<User, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();