1

Is it possible to reject all nginx request, which don't send basic authentication data with them?

I have requests like this:

xxx.xxx.xxx.xxx - - [24/Oct/2012:10:32:12 +0200] "POST /path HTTP/1.1" 401 1387 "-" "Apache-HttpClient/4.1.1 (java 1.5)" "-"
xxx.xxx.xxx.xxx - paul [24/Oct/2012:10:32:12 +0200] "POST /path HTTP/1.1" 200 192 "-" "Apache-HttpClient/4.1.1 (java 1.5)" "-"

and i want reject the first one, which don't provide the user. As you can see it already sends the 401 HTTP code, but this code is generated not directly from nginx but from an underlying application server. What I want to do is to directly deny it in nginx. Is there a way to check if a user has been provided?

And is this possible without setting up normal basic authentication directly in nginx?

disco crazy
  • 277
  • 6
  • 14

1 Answers1

2

Nginx stores the username derived from authentication in $remote_user. You should be able to test that it is not empty, and accordingly perform the desired action (e.g. return a 401 error). Something like:

if ($remote_user = ''){
    return 401;
}

By the looks of it, you are already populating the $remote_user variable (since it shows up in your logs) - as far as I know, you must use Nginx's HTTP Auth Basic Module to populate that variable.

Basic authentication sets the Authorization header. In Nginx, the HTTP request headers are accessible through $http_HEADER, so in this case $http_authorization. If you implement basic authentication outside of Nginx and set that header, you can test that the header is not empty. (Alternatively, depending on how you implement authentication, you could set a custom header that you test).

cyberx86
  • 20,805
  • 1
  • 62
  • 81