简体   繁体   中英

.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:

// 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 . 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.

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(); 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.

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:

 await _next.Invoke(context);

More details, refer to ASP.NET Core Middleware .

Change your RequestMiddleware as follow:

 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!"); 
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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