Skip to content

use as oauth reverse proxy for non ASGI apps #45

@ananis25

Description

@ananis25

Use-case:
Adding authentication to a non-python app running behind Nginx. Nginx provides an auth_request directive to authenticate all requests against an external service (link).

Change:
I tweaked the code here a tiny bit to use this app as the auth service. Nginx only accepts 200 and 4xx from authentication subrequests so we return a 401 when the user is not logged in and make Nginx redirect them to the login screen provided by this app.

@@ -109,11 +112,17 @@ class GitHubAuth:
         if scope.get("path") == self.callback_path:
             return await self.auth_callback(scope, receive, send)

+        login_path = "/-/login"
+        if scope.get("path") == login_path:
+            return await self.handle_require_auth(scope, receive, send)
+
         auth = self.auth_from_scope(scope)
         if auth or (not self.require_auth):
             await self.app(dict(scope, auth=auth), receive, send)
         else:
-            await self.handle_require_auth(scope, receive, send)
+            if self.non_asgi_proxy:
+                await send_html(send, 'redirect to login screen', status=401)
+            else:
+                await self.handle_require_auth(scope, receive, send)

Nginx config:

  location /login/ {
      auth_request off;      
      proxy_pass http://datasette-auth-github/;
  }

  location @errorlogin {
      return 302 /login/-/login;
  }

  location /secret/ {
      auth_request /login/;
      proxy_pass http://node-app/;
      error_page 401 = @errorlogin;
  }

Does this use-case make sense for the project? Happy to make a quick PR for it.
P.S. Thank you for writing this! I had difficulty grasping other python libraries doing OAuth.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions