Nginx - How can I create a custom request that will be used with the auth_request module

Viewed 2892

To start with: I am NOT an nginx expert. Very much a newbie to it.

I am attempting to protect a 3rd party piece of software with nginx doing the authentication (really - just verifying that the request has a valid OAuth2 Bearer token)

The HTTP request will have an OAuth2 bearer token in the Authentication header.

e.g. Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZ....H5w

I have an OAuth2 server (UAA) that has an api where I can call http://myuaa/check_token?token=eyJhbGciOiJSUzI1NiIsImtpZ....H5w to get back a 2XX or a 4XX if the token is valid. A complication is that this server does require basic auth to call the /check_token endpoint.

I have tried using a map to parse the token from the authorization header, but with no luck.

Just kind of at a loss.

Perhaps this isn't a good fit for Nginx?

relevant pieces of the nginx.conf

# this map isnt working as I thought it might
http {
    ...
    map $http_authorization $token {
        ~Bearer(?<token>abc)    $token;
 }

...

# test just to see if the authorization header is being parsed and passed - no luck
 location /oauth {
         proxy_set_header X-my-header $token;
         proxy_set_header X-another-header value;
         proxy_set_header Authorization "Basic basdasdfasdf";
         proxy_pass http://localhost:8080;
 }

Expected request to the 3rd party server that nginx is protecting:

<GET|POST|PUT|DELETE> /anyurl HTTP1/1.1
..
Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZ....H5w
..

Expected request forwarded to the UAA server to validate token

GET /check_token?token=eyJhbGciOiJSUzI1NiIsImtpZ....H5w
..
Authorization Basic asfasdfdf
..
1 Answers

Your map directive isn't working, named group token somehow interfere with the $token variable, any of these definitions would work:

map $http_authorization $token {
    ~^Bearer\s+([\S]+)$ $1;
}

or

map $http_authorization $token {
    ~^Bearer\s+(?<bearer>[\S]+)$ $bearer;
}

Full working config will be looking like this:

map $http_authorization $token {
    ~^Bearer\s+(?<bearer>[\S]+)$ $bearer;
}

server {
    ...
    location / {
        auth_request            /uaa;
        ...
    }
    location /uaa {
        internal;
        proxy_pass_request_body off;
        proxy_set_header        Authorization "Basic your_base64_auth_string";
        proxy_set_header        Content-Length "";
        proxy_pass              http://localhost:8080/check_token?token=$token;
    }
}
Related