首页 > 解决方案 > 根据服务类中的条件向客户端发送 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 错误..

请建议

标签: c#asp.net-core

解决方案


推荐阅读