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

相关内容

热门资讯

WPK辅助手段!智星菠萝辅助,... WPK辅助手段!智星菠萝辅助,德州微扑克总是是有辅助器技巧1、超多福利:超高返利,海量正版游戏,智星...
WPK辅助器窍要!aapoke... WPK辅助器窍要!aapoker辅助工具免费下载,德州微扑克都是存在有透视挂插件1、下载好aapok...
WPK安卓攻略!wepoker... WPK安卓攻略!wepoker究竟有没有透视,德州微扑克果然是有开挂脚本1、wepoker究竟有没有...
WPK俱乐部绝活!aapoke... WPK俱乐部绝活!aapoker透视脚本下载,德州微扑克都是是真的有辅助器神器1、用户打开应用后不用...
WPK模拟器指南书!wepok... WPK模拟器指南书!wepoker智能辅助插件,德州微扑克好像真的是有辅助app1、每一步都需要思考...
WPK模拟器方针!wepoke... WPK模拟器方针!wepoker透视最简单三个步骤,德州微扑克好像真的有开挂教程1、wepoker透...
WPK辅助器方针!wepoke... WPK辅助器方针!wepoker手机版透视脚本,德州微扑克切实真的有辅助器工具wepoker手机版透...
WPK辅助器课程!wejoke... WPK辅助器课程!wejoker私人辅助软件,德州微扑克其实真的是有辅助器攻略1、超多福利:超高返利...
WPK模拟器项目!德普之星怎么... WPK模拟器项目!德普之星怎么作弊,德州微扑克都是真的有透视脚本1、让任何用户在无需德普之星怎么作弊...
WPK辅助绝活!hhpoker... WPK辅助绝活!hhpoker怎么开透视,德州微扑克其实是有透视挂脚本1、下载好hhpoker怎么开...