在API中使用Identity

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:

7b316ae6ecd59bf28f521e0aeb91b915.png

同时也把本例中用到的唯一张表创建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

68c67dfb084cc8ad8592fb4b4f8314bf.png

登录API:

f8e962b9e09f9d4081b0e0623593a807.png

访问一个有鉴权的API:

b8b8709f5f1822d5c563b91858d53799.png

用RefreshToken来获取AccessToken的API:

1a33101c50f8dc960e64ed854638b0a0.png

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

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

ASP.NET Core Identity

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值