asp.net core使用identity+jwt保護你的webapi(一)——identity基礎配置


前言

用戶模塊幾乎是每個系統必備的基礎功能,如果每次開發一個新項目時都要做個用戶模塊,確實非常無聊。好在asp.net core給我們提供了Identity,使用起來也是比較方便,如果對用戶這塊需求不是非常個性化的話,identity是一個不錯的選擇。

ASP.NET Core Identity:

  • 是一個 API,它支持用戶 登錄功能(UI界面) 。

  • 管理用戶、密碼、配置文件數據、角色、聲明、令牌、電子郵件確認等。

Web API中集成Identity

identity是支持UI界面的,如果不是前后端分離項目,可以直接集成identity UI模塊,因為我這里使用Web API,就忽略掉identity UI部分。

安裝相關包

下面介紹以最小化方式引入identity。

首先創建一個Web API空項目,NuGet安裝identity、efcore、jwt相關包,數據庫我這里就使用Sqlite:

<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.10" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.10" />

自定義User,Context

創建自己的User實體,繼承IdentityUserIdentityUser中已經有一些基礎字段,你可以在你的AppUser中額外定義一些自己需要的字段,比如Address

public class AppUser : IdentityUser
{
    [Required] 
    [StringLength(128)] 
    public string Address { get; set; }
}

創建自己的DbContext,繼承IdentityDbContext<>,泛型傳入自己的AppUser

public class AppDbContext : IdentityDbContext<AppUser>
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }
}

在Startup中配置服務:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    services.AddDbContext<AppDbContext>(options =>
        options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
    
    services.AddIdentityCore<AppUser>().AddEntityFrameworkStores<AppDbContext>();
}

appsettings.json:

"ConnectionStrings": {
  "DefaultConnection": "DataSource=app.db; Cache=Shared"
}

這樣一個最簡單的自定義配置就完成了。

數據庫遷移

使用dotnet ef命令遷移:

dotnet ef migrations add AppDbContext_Initial

dotnet ef database update

執行完成后已經生成了identity相關表:

image-20210927210147461

修改主鍵類型/表名

identity用戶,角色表的主鍵默認類型是string,默認值是Guid.NewGuid().ToString(),數據量不大時無所謂,否則可能存在性能問題。identity支持主鍵類型的修改;想要修改表名,修改字段長度等等,也是非常容易:

public class AppUser : IdentityUser<int>
{
    [Required] 
    [StringLength(128)] 
    public string Address { get; set; }
}
public class AppDbContext : IdentityDbContext<AppUser, IdentityRole<int>, int>
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        
        builder.Entity<AppUser>(b => { b.ToTable("AppUsers"); });
        builder.Entity<IdentityUserClaim<int>>(b => { b.ToTable("AppUserClaims"); });
        builder.Entity<IdentityUserLogin<int>>(b => { b.ToTable("AppUserLogins"); });
        builder.Entity<IdentityUserToken<int>>(b => { b.ToTable("AppUserTokens"); });
        builder.Entity<IdentityRole<int>>(b => { b.ToTable("AppRoles"); });
        builder.Entity<IdentityRoleClaim<int>>(b => { b.ToTable("AppRoleClaims"); });
        builder.Entity<IdentityUserRole<int>>(b => { b.ToTable("AppUserRoles"); });
    }
}

修改完成后更新數據庫:

dotnet ef migrations add AppDbContext_Modify_PK_Type

dotnet ef database update

查看主鍵,表名已成功修改:

image-20210927212546938

最后

本篇完成了identity的基本配置,下一篇將介紹如何使用identity完成用戶注冊登錄,以及獲取jwt token。

參考:

ASP.NET Core 簡介 Identity | Microsoft Docs

Mohamad Lawand - DEV Community


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM