ASP.NET Core Identity Library

Create application user in Models namespace

using Microsoft.AspNetCore.Identity;

namespace xxx.Models
{
    public class xxxUser : IdentityUser
    {
    }
}

 

Inherit from IdentityDbContext in Data namespace

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace xxx.Data
{
    public class xxxDbContext : IdentityDbContext<xxxUser>
    {
        public xxxDbContext(DbContextOptions<xxxDbContext> options) : base(options)
        {

        }
    }
}

 

Register DbContect and Identity from Startup.ConfigureServices

services.AddDbContext<xxxDbContext>(options =>
            {
                options.UseMySql(Configuration.GetConnectionString("xxxDbContext"), ServerVersion.AutoDetect(Configuration.GetConnectionString("xxxDbContext")));
            });

            services.AddIdentity<xxxUser, IdentityRole>().AddEntityFrameworkStores<xxxDbContext>();


Use default Cookie Authentication in Startup.Configure

app.UseAuthentication();
app.UseAuthorization();


Customize JWT authentication in Startup.ConfigureServices

services.AddAuthentication(c =>
            {
                c.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                c.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                c.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(c =>
            {
                c.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Jwt:Issuer"],
                    ValidAudience = Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecurityKey"])),
                };
            });
创建时间:6/26/2022 12:13:09 AM 修改时间:6/26/2022 12:17:01 AM