Mark Yeltsin
Mark Yeltsin

Reputation: 131

Nginx Microservices Authentication

What's the best practice to build microservices authentication over Nginx?

At the moment I have the next reverse-proxy service

server {
    listen 80;
    listen [::]:80;

    server_name sspay.local;

    location /service/passport/ {
        proxy_pass http://passport-service:3000/;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $server_name;
    }
}

For example I want to create "user-serivce" which will be giving information about users. And I want it to give information about current user for ordinary user and information about all users for admins.

For this opportunity passport service gives JWT token that contains rights information for user.

So how I can create "a middleware" inside nginx which will do requests to "passport-service" to check if current JWT token has rights to access specified routes (ex., "/service/users/{id}")

Upvotes: 2

Views: 3398

Answers (1)

miknik
miknik

Reputation: 5941

Use the Nginx auth request module

Then set up your directives in Nginx something like this:

location /service/users/ {
    auth_request /auth;
    ...
}

location = /auth {
    internal;
    proxy_pass http://passport-service:3000/;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_set_header X-Real-Ip $remote_addr;
    proxy_set_header Authorization $http_authorization;
}

Now Nginx will make an internal subrequest to /auth whenever a client request url begins with /service/users, in this example passing the client IP and the authorization token in the headers, but you can configure it however to suit your needs.

Your authentication server script receives the subrequest, does whatever authentication you need to do and you code it to return HTTP response code of 200 if you want to allow access and 401 if you dont.

This is just a basic example which will allow or deny access, you can incorporate the error_page and/or auth_request_set directives to build a more comprehensive solution to redirect clients to a login page, custom error page, non admin page, whatever.

Upvotes: 3

Related Questions