Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set up an automatic authentication layer in nginx?

I'm building an ecosystem of applications under a common domain, with each application under a separate subdomain. I have built an authentication application for the ecosystem, but it requires each other application to be specially configured to use it. Is there a way to configure nginx to manage user sessions, possibly forwarding user information as headers to the various applications?

like image 296
Zikes Avatar asked Aug 16 '14 13:08

Zikes


People also ask

How does nginx Auth_request work?

Using directive auth_request /auth css , NGINX will send a GET request to /auth and listen to the response. This is done with the auth_request directive. A 201 response from /auth is a successful authentication and the /* contents will be served as normal.

What is Auth_basic in nginx?

auth_basic. auth_basic_user_file. The ngx_http_auth_basic_module module allows limiting access to resources by validating the user name and password using the “HTTP Basic Authentication” protocol. Access can also be limited by address, by the result of subrequest, or by JWT.

What is nginx Auth_request?

The auth_request module sits between the internet and your backend server that nginx passes requests onto, and any time a request comes in, it first forwards the request to a separate server to check whether the user is authenticated, and uses the HTTP response to decide whether to allow the request to continue to the ...


1 Answers

Let me show you a common pattern for cross-application authentications you can use with Nginx:

1) Build standalone service called auth_service, work independently from the web applications as required

2) Each subdomain apps will have an individual location that proxies to the same authentication service

location = /auth {
  proxy_pass http://auth_service.localhost/authenticate;
  proxy_pass_request_body off;
  proxy_set_header Content-Length "";
  proxy_set_header X-Original-URI $request_uri;
}

3) Individual web app uses "/auth" location to pass login/pass (based on POST data, headers or temporary tokens)

4) Standalone service's handler "/authenticate" accepts web apps login/pass and returns 200 or 401 if failed

The root of this approach is "/auth" location sits on each own subdomain based application, the server side dispatches the call to the single authentication end point which can be re-used efficiently and you can avoid code duplication.

This module Auth Request is not build by default, but comes with source code. Before use just compile Nginx with --with-http_auth_request_module option.

UPDATE: Since Nginx 1.5.4 this plugin comes in standard distribution without require to compile it in separately.

like image 101
Anatoly Avatar answered Sep 30 '22 11:09

Anatoly