简体   繁体   English

.NET 核心 WebApi 从中间件向用户返回未经授权的代码

[英].NET Core WebApi return Unathorized code to user from middleware

I want to send user bad request code back when something goes wrong in middleware.当中间件出现问题时,我想向用户发送错误的请求代码。

My Startup.cs looks like this:我的Startup.cs看起来像这样:

// configure method 
                                                                                                         
if (env.IsDevelopment())                                                                                 
{                                                                                                        
    app.UseDeveloperExceptionPage();                                                                     
}                                                                                                        
                                                                                                                                                                                   
app.UseCors("CorsPolicy");                                                                               
app.UseMiddleware<RequestMiddleware>();                                                                  
app.UseMiddleware<SecondRequestMiddleware>();                                                                                                                                                    
app.UseRouting();                                                                                        
                                                                                                         
app.UseEndpoints(endpoints =>                                                                            
{                                                                                                        
    endpoints.MapControllers();                                                                                                                                           
});         

My middleware looks like this:我的中间件看起来像这样:

public class RequestMiddleware                                                                                                                     
{                                                                                                                                                  
    private readonly RequestDelegate _next;                                                                                                        
                                                                                                                                                   
    public RequestMiddleware(RequestDelegate next)                                                                                                 
    {                                                                                                                                              
        _next = next;                                                                                                                              
    }                                                                                                                                              
                                                                                                                                                   
    public async Task InvokeAsync(HttpContext context, IAuthInfoService authInfoService, IPowiadomieniaCacheService cacheService)                  
    {                                                                                                                                              
        string jwt = context.Request.Headers["custom_header"];                                                                                
        if (string.IsNullOrEmpty(jwt))                                                                                                             
        {
            // no jwt in headers so i want to return Unauthorized to user:
            await ReturnErrorResponse(HttpContext context);                      
        }                                                                                                                                          
    }                                                                                                                                              
                                                                                                                                                   
    private Task ReturnErrorResponse(HttpContext context)                                                                                          
    {                                                                                                                                              
        context.Response.ContentType = "application/json";                                                                                         
        context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;                                                                            
                                                                                                                                                   
        return Task.CompletedTask;                                                                                                                 
    }                                                                                                                                              
                                                                                                                                                                                                                                                                                       
}                                                                                                                                                  

But still i getting into my SecondRequestMiddleware .但我仍然进入我的SecondRequestMiddleware I want to return 401 Stauts Code to user, when there is no jwt in headers (thats what my RequestMiddleware checks) and stopped processing this request.当标头中没有jwt (这是我的RequestMiddleware检查的内容)并停止处理此请求时,我想将401 Stauts Code返回给用户。

How to validate request in middleware and if conditions passed, return error code / response to user?如何验证中间件中的请求,如果条件通过,返回错误代码/响应给用户?

You could modify your middleware to short circuit a request, like this.你可以修改你的中间件来短路请求,就像这样。 Where await context.Response.StartAsync();在哪里await context.Response.StartAsync(); will start a response and will not proceed further.将开始响应,不会继续进行。

public class RequestMiddleware
{
    private readonly RequestDelegate _next;
    public RequestMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context, IAuthInfoService authInfoService, IPowiadomieniaCacheService cacheService)
    {
        string jwt = context.Request.Headers["custom_header"];
        if (string.IsNullOrEmpty(jwt))
        {
            // no jwt in headers so i want to return Unauthorized to user:
            await ReturnErrorResponse(HttpContext context);
        }
        else
        {
            await _next(context);
        }
    }

    private async Task ReturnErrorResponse(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
        await context.Response.StartAsync();
    }
}

when there is no jwt in headers (thats what my RequestMiddleware checks) and stopped processing this request.当标头中没有 jwt(这是我的 RequestMiddleware 检查的内容)并停止处理此请求时。

You can terminate the request by writing the following:您可以通过编写以下内容来终止请求

await context.Response.WriteAsync("error message");

If the headers have the jwt, then you need to trigger the following middleware through the following statement, otherwise it will not be executed automatically:如果headers有jwt,那么需要通过如下语句触发下面的中间件,否则不会自动执行:

 await _next.Invoke(context);

More details, refer to ASP.NET Core Middleware .更多详细信息,请参考ASP.NET 核心中间件

Change your RequestMiddleware as follow:更改您的 RequestMiddleware 如下:

 public class RequestMiddleware
    {
        private readonly RequestDelegate _next;

        public RequestMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            string jwt = context.Request.Headers["custom_header"];
            if (string.IsNullOrEmpty(jwt))
            { 
                await ReturnErrorResponse(context);
            }
            else
            {
                await _next.Invoke(context);// call next middleware
            }
        }

        private async Task ReturnErrorResponse(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; 
            await context.Response.WriteAsync("error message!"); 
        }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM