ASPNetCore6MinimalAPIs中是否可以使用自定义RequireAuthorization和AllowAnonymous来进行自定义中间件身份验证?
创始人
2024-09-20 08:00:56
0

是的,ASP.Net Core 6允许我们定义自定义Authentication管道。 在Minimal API中,我们可以使用以下代码实现:

  1. 定义自定义中间件来实现身份验证

public static class AuthenticationMiddlewareExtensions { public static IApplicationBuilder UseAuthentication(this IApplicationBuilder app, string policyName = null) { return app.Use(async (context, next) => { if (context.Request.Headers.TryGetValue("Authorization", out var authHeader)) { var authHeaderValue = authHeader.FirstOrDefault(); //Authenticate the user here //If authenticated, add claims to the context user } else { context.Response.StatusCode = 401; await context.Response.WriteAsync("Unauthorized"); return; }

        await next();
    });
}

}

  1. 在Minimal API中使用自定义身份验证中间件

var builder = WebApplication.CreateBuilder();

builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen();

builder.Services.AddAuthorization(options => { options.AddPolicy("MyCustomPolicy", policy => { policy.RequireAuthenticatedUser(); }); });

var app = builder.Build();

app.UseAuthentication();

app.MapGet("/hello", () => "Hello, World!") .RequireAuthorization("MyCustomPolicy");

app.Run();

在上面的代码中,我们通过调用UseAuthentication方法将自定义身份验证中间件添加到ASP.NET Core 6 Minimal API中。 我们还在构建器中添加了Authorization服务,并在API管道中的路由中使用RequireAuthorization来指定哪些路由需要身份验证。

相关内容

热门资讯

透视免费!哈糖大菠萝软件下载,... 透视免费!哈糖大菠萝软件下载,大菠萝免费辅助器,玩家教你(有挂详情)1、构建自己的哈糖大菠萝软件下载...
透视智能ai!wejoker免... 透视智能ai!wejoker免费脚本,本然真的有挂(透视)2025新版(有挂详情)1、wejoker...
透视好友房!德州透视竞技联盟,... 透视好友房!德州透视竞技联盟,xpoker辅助助手,揭秘教程(有挂教程)德州透视竞技联盟辅助器中分为...
透视系统!aapoker真的假... 透视系统!aapoker真的假的,素来真的有挂(透视)切实教程(有挂细节);1、这是跨平台的aapo...
透视ai!佛手在线是不是有挂,... 透视ai!佛手在线是不是有挂,德州透视插件,2025新版技巧(有挂规律)1、在佛手在线是不是有挂ai...
透视脚本!德普之星透视辅助软件... 透视脚本!德普之星透视辅助软件下载,果然真的是有挂(透视)细节方法(有挂教程);1、完成德普之星透视...
透视辅助!来玩app 德州 辅... 透视辅助!来玩app 德州 辅助,拱趴大菠萝挂怎么安装,透明挂教程(有挂揭秘)1、任何拱趴大菠萝挂怎...
透视透视挂!wepoker作弊... 透视透视挂!wepoker作弊辅助,原来有挂(透视)2025新版(有挂工具);暗藏猫腻,小编详细说明...
透视挂透视!哈糖大菠萝万能挂,... 透视挂透视!哈糖大菠萝万能挂,pokermaster修改器,教你攻略(有挂脚本);1、构建自己的哈糖...
透视有挂!wepoker透视脚... 透视有挂!wepoker透视脚本,总是存在有挂(透视)可靠教程(有挂黑科技)在进入wepoker透视...