Authenticate against Active Directory using Perl
Perl 5 is a highly capable, feature-rich programming language with over 30 years of development. Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large scale development projects.
n this example, we will authenticate username and password against Microsoft Active Directory using Perl. In order to do this, we will need Net::LDAP module for Perl. To install Net::LDAP, we need to install CPANM first :
Install CPANM
cpan App::cpanminus
Install Net::LDAP
cpanm Net::LDAP
Now that we have the needed Perl module, we can include the module, and create/assign variables for user credentials that wewant to check :
1 use Net::LDAP; 2 3 $userName="DOMAIN\Name"; 4 $password="password";
NOTE
:
If we were going to pass variables through a web page, we must convert special characters that have been translated to their unicode equivalents back to ASCII. So we need to add the two lines to do some regex substitutions :
1 $password=~s/\%([A-Fa-f0-9]{2})/pack('C',hex($1))/seg; 2 $password=~s/+/ /g;
Next, we set the LDAP variables and see if we can connect and authenticate :
1 $host="xxx.xxx.xxx.xxx"; 2 3 $ldap=Net::LDAP->new($host) or die "Can't connect: $@"; 4 $message=$ldap->bind($userName, password=>$password); 5 $results=sprintf("%s",$message->error); 6 $message=$ldap->unbind;
Finally, to get the results, we check if the variable, $results contains the word "Success" :
1 if ($results=~/Success/) 2 { 3 print "connected"; 4 } 5 else 6 { 7 print "Incorrect"; 8 }
Here is the complete code
1 use Net::LDAP; 2 3 $userName="DOMAIN\Name"; 4 $password="password"; 5 6 $host="xxx.xxx.xxx.xxx"; 7 $ldap=Net::LDAP->new($host) or die "Can't connect: $@"; 8 $message=$ldap->bind($userName, password=>$password); 9 $results=sprintf("%s",$message->error); 10 $message=$ldap->unbind; 11 12 if ($results=~/Success/) 13 { 14 print "connected"; 15 } 16 else 17 { 18 print "Incorrect"; 19 }