简体   繁体   中英

Nginx reverse proxy - 405 POST

I have Asp.Net Core Web Api application, which uses "x-api-key" http header to authorize a person sending a request. I've setup filter as过滤器设置为

public void OnActionExecuting(ActionExecutingContext context)
{
    // Retrieve record with specified api key
    var api = dbContext.Apis
        .Include(a => a.User)
        .FirstOrDefault(a => a.Key.Equals(context.HttpContext.Request.Headers["x-api-key"]));

    // Check if record exists
    if (api is null)
    {
        context.Result = new UnauthorizedResult(); // short circuit and return 401
    }
}

It is working as expected on both GET and POST requests without nginx proxy, however as soon as I add nginx, I receive 405 Not Allowed on POST request if api key is invalid but 401 on GET (if api key is valid filter works as expected and passes execution to controller). Here is my proxy configuration

server {
    listen 80;

    location / {
        proxy_pass http://ctoxweb:5000;
    }
}

(Both nginx and web api are setup using docker). What's the problem and how to fix that?

I managed to fix this problem, however I don't know exactly why this happens, I suppose it's somehow related to nginx not allowing any method (except for GET) on static content.

My best guess is that nginx assumes that empty response body (which comes from new UnauthorizedResult() ) is static, though it's clearly supplied by backend. The way to fix it is as easy as supply some object to response body, for example

if (api is null)
{
    context.HttpContext.Response.ContentType = "application/json";
    context.Result = new UnautorizedObjectResult("{\"info\":\"no api key header present\"}");
}

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