龙空技术网

在API中使用Identity

桂素伟 645

前言:

眼前小伙伴们对“aspnet access”大致比较着重,兄弟们都想要知道一些“aspnet access”的相关资讯。那么小编同时在网摘上网罗了一些对于“aspnet access””的相关知识,希望各位老铁们能喜欢,看官们快快来学习一下吧!

Identity是在.net中一个很有历史感的身份验证技术,在.NetFramework2.0(不是.net core 2.0)就诞生了,本次.NET第7个预版,带到了API框架中。

Identity的使用很简单,添加授权验证的中间件,然后再添加Identity的中间件,同时增加它标志性的那几张表(存放用户,角度等信息),本例中是用sqlite来存放数据。

using Microsoft.AspNetCore.Identity;using Microsoft.AspNetCore.Identity.EntityFrameworkCore;using Microsoft.EntityFrameworkCore;using System.Security.Claims;var builder = WebApplication.CreateSlimBuilder(args);builder.Services.AddAuthentication().AddBearerToken(IdentityConstants.BearerScheme);builder.Services.AddAuthorizationBuilder();builder.Services.AddIdentityCore<IdentityUser>()                .AddEntityFrameworkStores<IdentityDbContext>()                .AddApiEndpoints();var dbPath = string.Format("Data Source={0}\\db.sqlite", Directory.GetCurrentDirectory());builder.Services.AddDbContext<IdentityDbContext>(options => options.UseSqlite(dbPath));var app = builder.Build();app.MapIdentityApi<IdentityUser>();app.MapGet("/", (ClaimsPrincipal user) => $"欢迎:{user.Identity!.Name}").RequireAuthorization();app.Run();

表名称如下,具体生成方式可参见EF的CodeFirst:

同时也把本例中用到的唯一张表创建SQL放上来,方便Demo

CREATE TABLE AspNetUsers (    Id                   TEXT    NOT NULL                                 CONSTRAINT PK_AspNetUsers PRIMARY KEY,    AccessFailedCount    INTEGER NOT NULL,    ConcurrencyStamp     TEXT,    Email                TEXT,    EmailConfirmed       INTEGER NOT NULL,    LockoutEnabled       INTEGER NOT NULL,    LockoutEnd           TEXT,    NormalizedEmail      TEXT,    NormalizedUserName   TEXT,    PasswordHash         TEXT,    PhoneNumber          TEXT,    PhoneNumberConfirmed INTEGER NOT NULL,    SecurityStamp        TEXT,    TwoFactorEnabled     INTEGER NOT NULL,    UserName             TEXT);

运行程序,接下来就可以测试下,下面是一个注射用户API

登录API:

访问一个有鉴权的API:

用RefreshToken来获取AccessToken的API:

Identity在API框架项目中还只是开始阶段,功能也非常有限,但对于一些小项目,开箱即用还是非常用好处的。

之前有一个关于Identity的系列,请参照:

ASP.NET Core Identity

桂兵兵,公众号:桂迹ASP.NET Core Identity 结束篇-附链接

标签: #aspnet access