Last active
February 28, 2017 15:57
-
-
Save stefb69/3b6c54413b7022512d58 to your computer and use it in GitHub Desktop.
Simple and per location customizable LDAP Authentication for nginx, using embedded perl and ngx_http_auth_request_module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
package LDAPAuth; | |
use nginx; | |
use Authen::Simple::LDAP; | |
use MIME::Base64; | |
sub handler { | |
my $r = shift; | |
my $ldapfilter = $r->variable('ldapauth_filter'); | |
my $ldaphost = $r->variable('ldapauth_server'); | |
my $ldapbase = $r->variable('ldapauth_basedn'); | |
my $ldapauth = Authen::Simple::LDAP->new( | |
host => $ldaphost, | |
basedn => $ldapbase, | |
filter => $ldapfilter | |
); | |
my ( $u, $p ) = split( ':', decode_base64( ( split( ' ', $r->header_in("Authorization") ) )[1] ) ); | |
# print STDERR $r->header_in("Authorization") . " - u: $u - p: $p - ldaphost: $ldaphost - ldapbase: $ldapbase - ldapfilter: $ldapfilter\n"; | |
$r->discard_request_body; | |
if ( defined $u && defined $p ) { | |
if ( $ldapauth->authenticate( $u, $p ) ) { | |
# successfull authentication | |
# print STDERR "Auth OK\n"; | |
$r->status(200); | |
$r->send_http_header; | |
} else { | |
# print STDERR "Auth Failed\n"; | |
$r->header_out( "WWW-Authenticate", 'Basic realm="Secured Zone"' ); | |
$r->status(401); | |
$r->send_http_header; | |
} | |
return OK; | |
} else { | |
# print STDERR "Wrong Parameters\n"; | |
$r->status(401); | |
$r->send_http_header; | |
return ERROR; | |
} | |
} | |
1; | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
perl_require LDAPAuth.pm; | |
set $ldapauth_server "ldap.example.com"; | |
server { | |
location /_auth { | |
internal; | |
perl LDAPAuth::handler; | |
} | |
location /protected { | |
satisfy any; | |
auth_basic "Protected by LDAP"; | |
auth_basic_user_file "htpasswd.dummy"; | |
set $ldapauth_basedn "dc=example,dc=com"; | |
set $ldapauth_filter "(&(objectClass=inetOrgPerson)(objectClass=posixAccount)(uid=%s))"; | |
auth_request /_auth; | |
} | |
} |
Hasn't your browser kept credentials in the cache ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The directives:
$r->header_out( "WWW-Authenticate", 'Basic realm="Secured Zone"' );
$r->status(401);
$r->send_http_header;
doesn't work for me.
I want the server to request authentication again if first time failed, how can it be done ?