Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CN-based client authentification with nginx. This emulates Apache's SSLRequire (%{SSL_CLIENT_S_DN_CN} in {"Really Me"})
map $ssl_client_s_dn $ssl_client_s_dn_cn {
default "";
~/CN=(?<CN>[^/]+) $CN;
}
server {
listen 80;
listen [::]:80;
listen 443 ssl;
listen [::]:443 ssl;
server_name foo.bar.com;
if ($scheme = http) {
return 301 https://$server_name$request_uri;
}
ssl_certificate /etc/ssl/$server_name;
ssl_certificate_key /some/where/private;
ssl_client_certificate /the/root/of/all/client/cas.pem
ssl_verify_depth 3;
ssl_verify_client optional;
location ~ ^/safe {
if ($ssl_client_verify != SUCCESS) {
return 401;
}
if ($ssl_client_s_dn_cn !~ "Really Me") {
return 401;
}
}
}
@tvdinh

This comment has been minimized.

Copy link

@tvdinh tvdinh commented Nov 8, 2018

@schtobia: Thanks for the gist. Have you considered this https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/, which basically concerns using "if" in "location" ? It does surprise me how this common CN-based client access control scenario is not so straight-forward in nginx...

@tvdinh

This comment has been minimized.

Copy link

@tvdinh tvdinh commented Nov 14, 2018

Update: Even "if" directive is troublesome as mentioned in the doc, they also said it would be ok if using with only "return" or "rewrite...". So the gist is still ok.

Thanks for the gist again.

@schtobia

This comment has been minimized.

Copy link
Owner Author

@schtobia schtobia commented Nov 23, 2018

Thanks for the comment. 👍 I know that if is considered evil, but at that time there was no other solution. Maybe there is now, but as this is a very exotic case for nginx, I doubt that. Hope you found it helpful!

@maresb

This comment has been minimized.

Copy link

@maresb maresb commented Aug 13, 2019

Since nginx release 1.11.6, the formatting of $ssl_client_s_dn has changed to use commas instead of slashes.

In this case, the following line should work:

~(^|,)CN=(?<CN>[^,]+) $CN;

(Note the two cases that CN= could occur either at the beginning of the line or following a , character.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment