auth_request_set
The `auth_request_set` directive sets a variable based on the response from an internal authentication request.
Description
The auth_request_set directive in NGINX is used to define a variable that will store the result of an internal authentication request. Typically, the directive takes two arguments: the name of the variable to be set and the response that you wish to examine (either a status code or a specific variable). In scenarios where the internal authentication request succeeds, the variable is set; if it fails, the variable remains unset or resets to an initial state.
This directive is particularly useful in combination with the auth_request directive, where it allows for more granular access control by evaluating the result of authentication requests. For example, based on the value of the variable set by auth_request_set, additional logic can be executed, allowing for varying access levels or error handling. If the authentication request results in a 2xx response, it signifies success, while any 4xx or 5xx response indicates failure, thereby allowing configurable responses to unauthorized access attempts. The placement of the auth_request_set directive is flexible, as it can be used within the http, server, or location contexts, providing extensive versatility for configuration.
Moreover, it is important to ensure that the internal authentication requests are correctly configured and reachable. The behavior of the added variable and how it interacts with other directives can significantly affect NGINX’s routing and access control behavior, which necessitates thorough testing when implementing it in production environments.
Config Example
location /protected {
auth_request /auth;
auth_request_set $auth_status $upstream_status;
error_page 401 = @error401;
}
location = /auth {
internal;
proxy_pass http://backend_auth;
}Ensure that the internal request URL in auth_request is correctly configured to avoid unreachable endpoints.
Be cautious of setting the variable based on a response when the request may not yield a valid response code, as this could lead to confusing behavior during access control evaluations.
The order of variables defined with auth_request_set can impact their availability in further processing; ensure they are set before being referenced.