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来指定哪些路由需要身份验证。

相关内容

热门资讯

最新技巧!wepoker怎么增... 最新技巧!wepoker怎么增加运气,hhpoker必备开挂,一贯真的有挂(今日头条)1)有没有挂:...
推荐攻略!hhpoker德州有... 推荐攻略!hhpoker德州有挂吗,德普之星私人局透视,都是是真的有挂(证实有挂)1、起透看视 辅助...
科普!wepoker怎么提高运... 科普!wepoker怎么提高运气,拱趴大菠萝有什么挂,一贯是有挂(今日头条)1、不需要AI权限,帮助...
盘点一款!wepoker辅助软... 盘点一款!wepoker辅助软件视频,来玩app破解,都是真的有挂(有挂解惑)一、wepoker辅助...
推荐十款!hhpoker是真的... 推荐十款!hhpoker是真的假的,wepoker怎么提高运气,本来真的有挂(有挂详情)脚本下载中分...
分享个大家!德扑圈有透视吗,微... 分享个大家!德扑圈有透视吗,微扑克透视脚本,本来有挂(有挂总结)1)免费钻石:进一步探索免费脚本大陆...
我来教大家!wpk辅助,wep... 我来教大家!wpk辅助,wepoker透视有没有,好像是真的有挂(真是有挂)1、上手简单,内置详细流...
实测揭晓!hhpoker德州挂... 实测揭晓!hhpoker德州挂真的有吗,福建大菠萝万能辅助器,好像是有挂(讲解有挂)1、下载好正确养...
科普攻略!wpk插件辅助,we... 科普攻略!wpk插件辅助,wepoker透视功能下载,确实有挂(揭秘有挂)透视方法中分为三种模型:靠...
揭秘关于!pokemmo手机版... 揭秘关于!pokemmo手机版脚本免费,wpk私人局辅助是真的吗,好像存在有挂(确实有挂)1)有没有...