.NET 7 身份验证和授权的变化

Auth:admin Date:2022-11-9 18:54:54 Cat:技术笔记


.NET 7 于今天发布了,在 ASP.NET Core 的身份验证和授权的配置上做了一些简化,变化如下:

配置登录验证的方式,从 .NET 6 的:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme);

变成了 .NET 7 的:

builder.Services.AddAuthentication().AddCookie();

ASP.NET Core 会自动对认证方案进行推断,从而省略了参数的配置。

对于登录验证和授权的中间件,.NET 7 中不再需要手动引入,框架会自动推断是否使用,因此,app.UseAuthentication()app.UseAuthorization()也就不再需要了。

从而,运行一个完整的 ASP.NET Core MVC 程序所需要的最简配置是这样的:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication().AddCookie(); // new feature
var app = builder.Build();
app.UseStaticFiles();
app.MapDefaultControllerRoute();
app.Run();

参考链接:https://auth0.com/blog/whats-new-in-dotnet-7-for-authentication-and-authorization/

标签:,