We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Setting auth_request based on request method

Hi,

I appreciate this isn't technically related to Phalcon, but I'm hoping someone here might know the answer to this.

I've implemented auth_request for a set of micro services I'm currently building and very much like this feature. I am, however, having a bit of an issue with specifying what calls need the auth request based on the request method.

For example, I need to try and set up the following:

  • GET /object - NO auth needed
  • POST /object - auth needed
  • PATCH /object - auth needed

I've normalised the endpoints for the sake of this example and there are more endpoints but this should be enough to explain the scenario.

I currently have the following:

location /object { 
    auth_request /auth; 
    auth_request_set $auth $upstream_http_x_auth; 

    proxy_pass https://object; # an upstream 
    proxy_set_header X-Real-IP $remote_addr; 
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
    proxy_set_header X-Auth $auth; 
    proxy_set_header Host $http_host; 
} 

I tried using an IF statement but got errors because of auth_request not being allowed there. How can I make it so that the GET request doesn't go through the auth request?

Thanks, Gary

edited Feb '17

You're right, this is an NGINX config question and has nothing to with Phalcon :]

server {
  location / {
    # This proxy_pass is used for requests that don't
    # match the limit_except
    proxy_pass https://127.0.0.1:8080;

    # For requests that *aren't* a PUT, POST, or DELETE,
    # pass to :9080
    limit_except PUT POST DELETE {
      proxy_pass https://127.0.0.1:9080;
    }
  }
}

https://stackoverflow.com/questions/8591600/nginx-proxy-pass-based-on-whether-request-method-is-post-put-or-delete#answer-8594977



6.5k
Accepted
answer

I had to use the nginx IRC channel in the end and got the following solution:

location /object {
    if ($request_method = GET ) {
        rewrite ^ /internal$uri last;
    }

    auth_request /auth;
    auth_request_set $auth $upstream_http_x_auth;

    proxy_pass https://object;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Auth $auth;
}

location /internal/object {
    internal;

    rewrite ^/internal(?<realurl>/.*)$ $realurl break;

    proxy_pass https://object;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Auth $auth;
}

Was hoping to avoid the if statement, but it will do for now at least.