@@ -0,0 +1,64 @@
1+{ pkgs, config, lib, ... }:
2+with lib;
3+let
4+ cfg = config.services.oauth2_proxy.nginx;
5+in
6+{
7+ options.services.oauth2_proxy.nginx = {
8+ proxy = mkOption {
9+ type = types.string;
10+ default = config.services.oauth2_proxy.httpAddress;
11+ description = ''
12+ The address of the reverse proxy endpoint for oauth2_proxy
13+ '';
14+ };
15+ virtualHosts = mkOption {
16+ type = types.listOf types.string;
17+ default = [];
18+ description = ''
19+ A list of nginx virtual hosts to put behind the oauth2 proxy
20+ '';
21+ };
22+ };
23+ config.services.oauth2_proxy = mkIf (cfg.virtualHosts != [] && (hasPrefix "127.0.0.1:" cfg.proxy)) {
24+ enable = true;
25+ };
26+ config.services.nginx = mkMerge ((optional (cfg.virtualHosts != []) {
27+ recommendedProxySettings = true; # needed because duplicate headers
28+ }) ++ (map (vhost: {
29+ virtualHosts.${vhost} = {
30+ locations."/oauth2/" = {
31+ proxyPass = cfg.proxy;
32+ extraConfig = ''
33+ proxy_set_header X-Scheme $scheme;
34+ proxy_set_header X-Auth-Request-Redirect $request_uri;
35+ '';
36+ };
37+ locations."/oauth2/auth" = {
38+ proxyPass = cfg.proxy;
39+ extraConfig = ''
40+ proxy_set_header X-Scheme $scheme;
41+ # nginx auth_request includes headers but not body
42+ proxy_set_header Content-Length "";
43+ proxy_pass_request_body off;
44+ '';
45+ };
46+ locations."/".extraConfig = ''
47+ auth_request /oauth2/auth;
48+ error_page 401 = /oauth2/sign_in;
49+
50+ # pass information via X-User and X-Email headers to backend,
51+ # requires running with --set-xauthrequest flag
52+ auth_request_set $user $upstream_http_x_auth_request_user;
53+ auth_request_set $email $upstream_http_x_auth_request_email;
54+ proxy_set_header X-User $user;
55+ proxy_set_header X-Email $email;
56+
57+ # if you enabled --cookie-refresh, this is needed for it to work with auth_request
58+ auth_request_set $auth_cookie $upstream_http_set_cookie;
59+ add_header Set-Cookie $auth_cookie;
60+ '';
61+
62+ };
63+ }) cfg.virtualHosts));
64+}