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

后端 未结 2 1796
南方客
南方客 2021-02-09 02:58

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

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-09 03:22

    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.

提交回复
热议问题