c# - 根据服务类中的条件向客户端发送 401/403 错误
问题描述
asp.net 5 授权(默认)在启动类。
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.RequireHttpsMetadata = true;
o.SaveToken = true;
.....
});
在他们的服务类我发送错误
var user = await _userManager.Users.Include(u=>u.Roles).Include(u => u.Bank).FirstOrDefaultAsync(u=>u.UserName == request.UserName);
var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, lockoutOnFailure: true);
if (result.IsLockedOut)
{
throw new ApiException("User Locked out / Inform admin");
}
if (!result.Succeeded)
{
throw new ApiException("Invalid UserName or Password"); //What exception details to send?
}
我已经为 ApiException 编写了异常处理程序中间件,如下所示
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception error)
{
var response = context.Response;
response.ContentType = "application/json";
var responseModel = new Response<string>(error?.Message);
switch (error)
{
case ApiException e:
// custom application error
response.StatusCode = (int) HttpStatusCode.BadRequest;
break;
....
default:
// unhandled error
response.StatusCode = (int) HttpStatusCode.InternalServerError;
break;
}
var result = JsonSerializer.Serialize(responseModel);
await response.WriteAsync(result);
}
}
现在我需要根据授权失败的情况在用户服务中发送自定义错误(401 和 403)。
我如何在 asp.net core (.net 5) 中向客户端发送 401 或 403 错误..
请建议
解决方案
推荐阅读
- java - 当您在另一个下拉框 Java 中选择不同的值时更改一个下拉框的值
- unetstack - 如何计算不在彼此直接范围内的两个节点之间的距离?
- python - 如何做一个在特征函数中选择某些特定行的比较器?
- python - 如何使用 numpy 数组有效地执行多个元素交换?
- javascript - 在cypress中下载pdf需要指导
- python - Jupyter 在同一目录中找不到 python 导入
- c# - WebClient 随机行为
- java - ZonedDateTime.parse(...) 与 ZonedDateTime.of(...)
- python - 我们如何检查时间序列中的预测准确性?
- java - 将 ArrayList 从 RecyclerView 传递到另一个 Activity