When running aspnet core 2.0 identity application, I have encountered the error "invalid object AspNetUsers", which means the database table is not created. In order to create database schema required by aspnet core 2.o identity framework, following these steps:
1. In your project, create data context related to identity:
1. In your project, create data context related to identity:
public class UserDbContext : IdentityDbContext<IdentityUser>
{
public UserDbContext(DbContextOptions<UserDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
2. In Startup.cs file, configure the Identity store and UserDbContext entity framework:
var secretKey = Configuration.GetSection("JWTSettings:SecretKey").Value;
var issuer = Configuration.GetSection("JWTSettings:Issuer").Value;
var audience = Configuration.GetSection("JWTSettings:Audience").Value;
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
// Validate the JWT Issuer (iss) claim
ValidateIssuer = true,
ValidIssuer = issuer,
// Validate the JWT Audience (aud) claim
ValidateAudience = true,
ValidAudience = audience
};
services.AddDbContext<DataContext>(
options => options.UseSqlServer(Configuration.GetSection("SqlConfig:ConnectionString").Value));
services.AddEntityFrameworkSqlServer()
.AddDbContext<UserDbContext>(options => options.UseSqlServer(Configuration.GetSection("SqlConfig:ConnectionString").Value));
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<UserDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication()
.AddCookie(o => {
o.SlidingExpiration = true;
o.ExpireTimeSpan = TimeSpan.FromMinutes(20);
o.LoginPath = new PathString("/Account/login");
}
)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = tokenValidationParameters;
});
3. Open Nuget manager console by click "Tools -> Nuget Package Manager -> Package Manager Console". Run following two command:
Add-Migration -context UserDbContext
Update-Database -context UserDbContext
Enjoy coding!
Comments