asp.net-core - 具有基本和 JWT 授权和自定义策略的 ASP.NET Core 3.1
问题描述
我需要在我的 ASP.NET Core 3.1 应用程序中同时拥有 JWT 和基本授权。
这是我的启动配置:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.ApiAuthenticationScheme;
...
});
services.AddAuthorization(options =>
{
options.AddPolicy("BasicAuth", policyBuilder =>
{
policyBuilder.Requirements.Add(new BasicAuthenticationRequirement());
});
options.AddPolicy("Customer", policyBuilder =>
{
policyBuilder.AuthenticationSchemes.Add(JwtBearerDefaults.ApiAuthenticationScheme);
policyBuilder.RequireRole("Customer");
});
});
还 :
services.AddTransient<IAuthorizationHandler, BasicAuthenticationHandler>();
我需要添加BasicAuthenticationHandler
,因为我需要访问IHttpContextAccessor
:
public BasicAuthenticationHandler(IHttpContextAccessor httpContextAccessor)
{
}
但这里的问题是,对于每个要授权的请求,即使它有 [Authorize(Policy = "Customer")] 它也不会考虑“JwtBearer”并跳过授权并运行操作。
更新
尽管它自己的操作具有 [Authorize] 属性,但控制器具有 [AllowAnonymous] 属性,当我将其从控制器中删除并让操作具有 [Authorize] 时,它起作用了。
解决方案
推荐阅读
- tensorflow - Tensorflow:如何理解 tflite 模型中的锚点?
- javascript - Javascript对象构造函数参数
- sql - 使用 T-SQL 处理不同模型的每日不同销售额
- javascript - 每次在 socket.io 上都越来越多地重复该过程
- mysql - Sequelize:如何急切加载,带有关联,原始:true?
- javascript - 如何提及使用 Chat Discord.JS 发送消息的用户?
- python - 如何修改它以从右到左读取并提取行?而不是从左到右阅读
- python - 如何按词频迭代列表和分组
- flutter - 设置为全屏模式时,Flutter 容器不会覆盖整个屏幕
- java - 为什么我的战争文件仍然复制和提取但没有在 tomcat docker 容器中运行