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

相关内容

热门资讯

透视曝光!pokemmo免费脚... 透视曝光!pokemmo免费脚本(透视)wepoker辅助是真的假的,教程模块(有挂助手)-哔哩哔哩...
透视推荐!hhpoker脚本(... 透视推荐!hhpoker脚本(透视)wepoker辅助是真的吗,教程技法(有挂秘笈)-哔哩哔哩;小薇...
透视解谜!wpk透视工作室(透... 透视解谜!wpk透视工作室(透视)德州局透视脚本下载安装最新版本,教程秘籍(有挂秘笈)-哔哩哔哩1、...
透视科普!hh poker插件... 透视科普!hh poker插件下载(透视)安装不了wepoker,教程大纲(有挂方略)-哔哩哔哩1、...
透视曝光!wepoker私人辅... 透视曝光!wepoker私人辅助器(透视)哈糖大菠萝攻略,教程烘培(有挂讲解)-哔哩哔哩1、下载好w...
透视曝光!wepoker有辅助... 透视曝光!wepoker有辅助功能吗(透视)pokemmo脚本辅助下载,教程教材(有挂方针)-哔哩哔...
透视解谜!约局吧透视脚本(透视... 透视解谜!约局吧透视脚本(透视)aapoker俱乐部靠谱吗,教程模板(有挂透视)-哔哩哔哩进入游戏-...
透视关于!wpk可以透视吗(透... 透视关于!wpk可以透视吗(透视)hardrock透视工具,教程技法(存在有挂)-哔哩哔哩1、打开软...
透视详情!wepoker怎么设... 透视详情!wepoker怎么设置盖牌(透视)aapoker如何设置胜率,教程讲义(有挂透视)-哔哩哔...
透视详细!aapoker辅助器... 透视详细!aapoker辅助器是真的吗(透视)wepoker轻量版有透视吗,教程手筋(有挂头条)-哔...