惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 司徒正美
Blog — PlanetScale
Blog — PlanetScale
博客园 - 聂微东
月光博客
月光博客
量子位
大猫的无限游戏
大猫的无限游戏
Stack Overflow Blog
Stack Overflow Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Cloudflare Blog
P
Proofpoint News Feed
B
Blog RSS Feed
美团技术团队
腾讯CDC
C
Check Point Blog
Engineering at Meta
Engineering at Meta
F
Fortinet All Blogs
N
Netflix TechBlog - Medium
Recent Announcements
Recent Announcements
J
Java Code Geeks
S
SegmentFault 最新的问题
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享

博客园 - hrx521

微信公众号H5开发踩坑记:为什么POST返回的页面会显示HTML源码 SQL NOT IN 子查询存在 NULL 的经典行为陷阱--NULL 三值逻辑(TRUE / FALSE / UNKNOWN) SQL用窗口函数做逐行累计的实用用例 我的蝶翼斑马鱼繁殖要领总结 如何从操作系统的角度,理解C#语言的Async Await 异步机制内部状态机的运行原理? C#扩展方法对软件工程构建的促进示例和总结 基于原数据库新创建一个带部分数据做为初始数据的数据库的思路 sql调优记录,不要在join on 条件中使用过多的条件 发布和更新自己的nuget包 Rust的枚举类型Enum Rust语言特色语法记录 Rustup-init.exe安装后执行cargo run 报错:`link.exe` returned an unexpected error的解决办法 FastReport.OpenSource .Net下开源免费报表打印组件 SQL使用Merge在一个语句中完成插入、更新和删除操作 IIS应用程序回收导致应用中Hangfire等后台任务无法正常启动工作的解决方法 C# xml文档反序列化记事 债券与债券基金 Linq补充学习 Blazor学习记录_12._IIS部署_组件的引用_HTML元素的引用 Blazor学习记录_11.身份认证与授权 Blazor学习记录_10.C#和JS互操作_访问WEB API Blazor学习记录_9.预呈现_渲染树
Microsoft.AspNetCore.Identity 的使用记录
hrx521 · 2024-06-19 · via 博客园 - hrx521

使用方法

引入包:

    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0-rc.2.23480.2" />
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0-rtm.23502.22" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.0-rc.2.23480.1" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />

以上代码中引用的OpenApi包的作用是什么暂不清楚。

代码:

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

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Authorization
builder.Services.AddAuthorization();

// Configure identity database access via EF Core.
builder.Services.AddDbContext<ApplicationDbContext>(
    options => options.UseInMemoryDatabase("AppDb"));

// Activate identity APIs. By default, both cookies and proprietary tokens
// are activated. Cookies will be issued based on the `useCookies` querystring
// parameter in the login endpoint.
builder.Services.AddIdentityApiEndpoints<IdentityUser>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi()
.RequireAuthorization();

app.MapIdentityApi<IdentityUser>();

app.Run();

public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) :
        base(options) { }
}

internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

以上代码,同时支持cookie和简单的访问令牌方式。

一些说明

使用Cookie

在发起请求时从浏览器附加Cookie的示例图:
请求后自动生成Cookie,缓存保存于浏览器中
image
以后每次发起请求时浏览器都会自动为请求附加其缓存的Cookies
image

使用访问令牌 bearer token

在发起请求时附加了Authorization请求头,示例
注意,如果手动传参,Head中Authorizaion的值要以 Bearer 开头加空格再加Token值,并且Bearer必须大写。
image

官方文档参考:
https://learn.microsoft.com/zh-cn/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-8.0

SPA的示例 Web API 后端,官方示例代码:
https://github.com/dotnet/AspNetCore.Docs.Samples/blob/main/samples/SimpleAuthCookiesAndTokens/SimpleAuthCookiesAndTokens/Program.cs