asp.net-core-webapi - 如何在 Ocelot 和 .Net WebApi 中覆盖 AuthorizationMiddleware 时返回未经授权的响应
问题描述
我正在尝试使用 .NET 5 WebApi 中的 OcelotPipelineConfiguration 覆盖 Ocelot AuthorizationMiddleware。这是我的代码:
更新
配置
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAuthorizationService authorizationService)
{
if (env.EnvironmentName == Environments.Development)
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
var configuration = new OcelotPipelineConfiguration
{
AuthorizationMiddleware = async (ctx, next) =>
{
if (! await authorizationService.IsValid(ctx))
{
ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await ctx.Response.WriteAsync("Some Error !");
}
else
{
await next.Invoke();
}
},
};
app.UseOcelot(configuration).Wait();
}
更新
配置服务
public void ConfigureServices(IServiceCollection services)
{
string AuthenticationKey = "AuthenticationKey";
services.AddLogging();
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(AuthenticationKey, option =>
{
option.RequireHttpsMetadata = true;
option.SaveToken = true;
option.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey =
new SymmetricSecurityKey(
Encoding.ASCII.GetBytes(Configuration.GetSection("SecretKey").Value)),
ValidateIssuerSigningKey = true,
ValidateIssuer = false,
ValidateAudience = false
};
//option.ForwardSignIn
});
services.AddHttpClient<IAuthorizationService, AuthorizationService>();
services.AddScoped<IJWTHelpers, JWTHelpers>();
services
.AddOcelot()
.AddDelegatingHandler<HeaderDelegatingHandler>();
services.AddMvc();
}
如您所见,在某些情况下,我需要立即返回类似Unauthorized的响应,但我的代码总是向 Postman返回500 Internal Server Error 。我搜索了很多,发现了这个问题。但我在 HTTPContext 中找不到Errors.Add方法。是否有任何想法可以立即返回未经授权的响应?
解决方案
我通过@Artur 评论找到了正确答案。我换了
ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await ctx.Response.WriteAsync("Some Error !");
在用这个配置方法:
ctx.Items.SetError(new UnauthorizedError("your custom message"));
return;
推荐阅读
- javascript - Quasar SSR:使用引导文件将 HTML 内容注入 index.html
- python - 将两列与 None 进行比较,其中一列中的 None 与另一列的计数不同
- sql - 在不影响代码的情况下转换表格设计
- php - 如何使用 preg_match 和 preg_replace 在带有破折号的字符串中添加和附加任何数字组?
- linux - 在 nginx 上提供外部文件
- if-statement - 用累积计数替换单元格
- ruby-on-rails - Bootstrap 徽章颜色在 Rails 中不起作用
- google-apps-script - 从 GetRangeByName 获取范围,激活范围
- class - C++ 中的类中的类
- cassandra - 如何使用 TWCS 和计数器列从 Cassandra 表中删除数据?