使用方法

引入包:

    <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

posted on 2024-06-19 20:26  hrx521  阅读(1)  评论(0编辑  收藏  举报