Php authentication with active directory

PHP Active Directory authentication with Kerberos

then just let the browser & webserver handle the authentication and use some PHP like: Now you can do SSO using Kerberos, works a charm. This specific Active Directory only allows authentication through Kerberos, or ldaps:// (but this last one is not the most wanted since I’ll have to use absolute paths).

PHP Active Directory authentication with Kerberos

I’m currently integrating a CMS (developed in PHP) authentication with Active Directory. This specific Active Directory only allows authentication through Kerberos, or ldaps:// (but this last one is not the most wanted since I’ll have to use absolute paths).

I’ve been searching the web for anything about PHP AD Kerberos Authentication, but found nothing. Can anyone point me in the right direction?

If you are using Active Directory, its possible your webserver is IIS, which has inbuilt kerberos*.. then just let the browser & webserver handle the authentication and use some PHP like:

$user = isset($_SERVER['AUTH_USER']) ? $_SERVER['AUTH_USER'] : false; if((false === $user) or ('' == $user)) < //Divert to incorrect password page.. //MSIE typically tries three times, Kerb/NTLM/Plain //FF will only try NTLM/Plain if configured for NTLM //Chrome.. won't work with this at all.. not that I have discovered. //If testing locally using Apache, user will be 0 >

Now you can do SSO using Kerberos, works a charm.

*: Called «Integrated Windows Authentication» http://support.microsoft.com/kb/324274 and must be enabled in browser by setting «Security Zone» to «Local Intranet».. which may happen if the IIS box is actually on the local intranet.. but it depends on the SPN and the domain the User’s box and IIS box and any trust relationships.. if its on a single domain with the domain name/machine name the same it should work. If you are clustering or anything fun, expect a major headache, rather than just a normal headache. You can script/GPO the IE settings if you feel the need..

Hopefully you are asking about something else.. If I prayed it would be that you didn’t implement this, it causes the whole authentication process for every single request.. which turns out slows down every page load.. no matter how many aggregations/hacks/workarounds you implement.. it was just a bad idea, but once you start or tell a manager about it, they really love it because it saves them having to login again.. oh, they will still complain about speed, but..

Not freeware solution — google by ‘Plexcel’ keyword

There’s a krb5 module for PHP. It has a PECL entry although no packaging yet. You can find out more about it here:

Authenticating to webservice with Kerberos from PHP in, I am writing a PHP webapplication that has to connect to a webservice using Kerberos 5 authentication (Active Directory). My PHP website is hosted on IIS 7.5 with PHP 5.5. The application pool is running under the account that is authorized in Active Directory and for the target webservice. I tried every …

Читайте также:  background-position

PHP Kerberos: Check for valid ticket/Access the ticket

We have an apache2-server using Kerberos for website-authentication via Active Directory. On the website i use the Drupal-Framework and the unsupported «Kerberos Authentication»-Module (https://www.drupal.org/project/kerberos_authentication).

When a user wants to access the Website, she/he has to do the following:

  1. Open the browser & navigate to the website
  2. A popup appears asking for Kerberos/AD credentials. ( )
  3. Enter AD credentials
  4. Being allowed to proceed to the drupal-website.
  5. Access the website

The problem is in Part 5: The user still needs to fill in the login-form to get logged into drupal. The AD username and password are working here thanks to the Drupal-Kerberos-Module. But this forfeits Kerberos in the first place, since the users have to enter their credentials more than once.

How can i access the ticket the user was granted/that is stored in the browser (or wherever it is stored) using php? Or how to check if a user as a valid Kerberos ticket so that the user does not have to enter his login data twice and gets logged into drupal automatically, using php? (I am aware that this could require me to write my own drupal module)

Tangential to your question — though I’ve never managed to properly configure the module you mention, I’ve had great luck with the LDAP module. It also includes a submodule for SSO, which does exactly what you want, but using the Drupal login form as a fallback instead of the (in my opinion, ugly) popup shown in your example.

Pykerberos, High-level interface to Kerberos. This Python package is a high-level wrapper for Kerberos (GSSAPI) operations.

Using Kerberos for SSO on Webpages

I’m not very practised in using Kerberos. But I want to implement a single-sign-on with Kerberos.

The aim I want to achieve is, that you only have to login with Windows 7 and then open the browser and there is no other authetification required, e.g. for a intranet. Is this possible?

Kerberos is using tickets. The first step is geting the ticket granting ticket, isn’t it? And Windows Server is using Kerberos for authentification. So is there a ticket granting ticket after the login in Windows? Can I use this (if there is one) for getting a service ticket for other services?

Another question is about apache: When I use Kerberos with a linux server, I need a mod named mod_auth_kerb, isn’t it? If this is installed on my linux server, can I use Kerberos-authentification? If there is a intranet on the linux server, how is it possible to authentificate with kerberos. Should I authentificate in the PHP code or is it e.g. possible to «learn» apache to authentificate in some way?

Yes, this is all possible and done all the time. When you log into a domain account, Windows acquires a Kerberos credential (ticket-granting ticket or TGT) from a domain controller using your password, which in turn allows you to get tickets for other services without re-entering your password. You can see the TGT and any other tickets you have for specific services with klist.exe. Web browsers use the HTTP Negotiate exchange to send a ticket to the web server, which the server can use to identify you (an optional return token can also authenticate the server to the client). The server must be a member of the same kerberos realm, or one which has a chain of realm trusts to yours.

Читайте также:  Css язык программирования примеры

mod_auth_kerb is the most common module used for Kerberos authentication in Apache. You would add a Kerberos principal for the web server to an AD account using setspn.exe, of the form HTTP/server-hostname. Then create a file holding that principal’s keys, called a «keytab,» using ktpass.exe on Windows or a program like ktutil on Unix (for which you need the AD account’s password). The mod_auth_kerb configuration refers to the keytab. mod_auth_kerb sets the environment variable REMOTE_USER to the client’s identification, and you would just read that in your application (PHP code in this case).

You must configure the web browser to actually use HTTP Negotiate authentication, the details of which vary from one browser to another.

This is just answering your immediate questions in a high-level way; there are lots of other details involved, of course, since you’re dealing with a whole infrastructure and several parts which have to be coordinated: Kerberos, DNS names, principal names, browser configuration, Apache, etc.

By the way: the word in English is «authenticate,» not «authentificate.»

PHP Active Directory authentication with Kerberos, I’m currently integrating a CMS (developed in PHP) authentication with Active Directory. This specific Active Directory only allows authentication through Kerberos, or ldaps:// (but this last one is not the most wanted since I’ll have to use absolute paths). Code sample$user = isset($_SERVER[‘AUTH_USER’]) ? $_SERVER[‘AUTH_USER’] : false;if((false === $user) or (» == $user))<>Feedback

PHP Kerberos delegate to SQL Server

Is there a way to delegate session from Kerberos authentication on Apache + PHP to a SQL server connection? We want to accomplish user based connection to SQL server.

No, the PHP MSSQL and ODBC extensions do not provide kerberos authentication.

What could work is running PHP in IIS and using the PHP COM extension to use ADODB.Connection and follow the steps explained here: http://support.microsoft.com/kb/319723

Php — CakePHP and Kerberos, I have a web app built upon CakePHP. Currently it is doing user authentication / Access Control with the built-in AuthComponent and the ACL functionality. Throughout our organization, we have MANY

Источник

Php authentication with active directory

Здесь рассмотрим выполнение сквозной авторизации пользователя в Active Directory C получением параметров пользователя.
Необходимым условием является наличие пользователя в домене, т.е. пользователь не прописанный в домене не пройдет авторизацию.
Прежде всего необходимо установить соединение нашего php-скрипта с доменом.
Подразумевается, что в AD прописан не только пользователь, но и компьютер пользователя.
Часто в описании пользователя отсутсвует привязка к компьютеру, — этот скрипт проверяет сведения о компьтере в домене и вытягивает всю необходимую информацию.
Сделаем это следующим образом:
1. Получаем имя удаленного хоста, при входе пользователя на страницу.

$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']); //echo $hostname;

2. Поскольку полученное имя может быть длинее 15 символов (а именно столько позволяет внести NETBIOS-имя), — обрезаем до необходимой длнины, убираем все символы после первой точки (т.к. полученное имя имя будет иметь формат «логин.субдомен.домен») и в переменную «текущий пользователь» берем результат, добавляя к нему спецсимвол «$».

$hostname = substr($hostname, 0, 15); list($hostname,) = explode('.',$hostname); $cur_user=$hostname."$"; //echo $cur_user;

3. Устанавливаем соединение с доменом.
Для этого используем пару «логин-пароль» имеющие права считать информацию из AD.

$ds=ldap_connect("ldap-имя.домен"); // Необходимо указать корректный LDAP сервер ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); // версия протокола зависит от настрое домена, в моем случае = 3 if ($ds) < $r=ldap_bind($ds, "логин@домен" ,"пароль"); // не анонимная привязка, /* тут выполняем операции по выборке данных из AD (описаны в пунктах 4 и 5) */ >else < echo "<h4>Невозможно подключиться к серверу LDAP</h4>"; >

Получение информации из домена разделим на две составляющие: информация о компьютере и информация о пользователе.
4. Извлечение информации о копьютере.
Эту операцию выполнит следующий код:

$sr=ldap_search($ds, "OU=ESRR, DC=esrr, DC=oao, DC=rzd", "samaccountname=".$cur_user); // живой пример $info = ldap_get_entries($ds, $sr); //print_r($info); // выведет всю доступную информацию, из которой и извлечем данные for ($i=0; $i&lt;$info["count"]; $i++) < $komp2000=iconv('utf-8', 'cp1251',$info[$i]["name"][0]); // имя компьютера в формате windows 2000 (соответсвует NETBIOS-имени) $dnsname=iconv('utf-8', 'cp1251',$info[$i]["dnshostname"][0]); // DNS-имя компьтера в домене. >//echo "Имя компа : ".$komp2000.""; //echo "Полный DNS компа : ".$dnsname.""; list($dnsname,) = explode('.',$dnsname); //echo "Краткий DNS компа : ".$dnsname.""; // В моем случае компьютеры записаны в домене в формате "префикс-имя компа", а пользователи - "префикс-имя пользователя", при этом имя компа = имя пользователя, поэтому выполняю операцию замены символа. $userlogin=str_replace('-','_',$dnsname); // получил логин $pref = explode("_", $userlogin); // получил префикс $upref = $pref[0]; // echo "pr : ".$upref."; //echo "Логин пользователя : ".$userlogin.";

5. Извлечение информации о пользователе (в качестве продолжения кода приведенного в п.4)

$sr2=ldap_search($ds, "OU=ESRR, DC=esrr, DC=oao, DC=rzd", "sAMAccountName=".mb_strtolower($userlogin));// живой пример // тут mb_strtolower - игнорирование регистра символов $info2 = ldap_get_entries($ds, $sr2); for ($i=0; $i&lt;$info2["count"]; $i++) < $fioful=iconv('utf-8', 'cp1251',$info2[$i]["cn"][0]); $company=iconv('utf-8', 'cp1251',$info2[$i]["company"][0]); >//echo "Полное имя пользователя : ".$fioful; //echo "Предприятие пользователя : ".$company;

Выше приведенный способ я использовал по причине запрета доменной политикой использования в браузере ActiveX.
Если же ActiveX у вас разрешен — можно использовать другой способ извлечения из AD информации о пользователе посетившем web-страницу, приведенный ниже:

<script type="text/javascript"> var CurentUser = new ActiveXObject('WScript.Network'); var Param = CurentUser.UserName; document.write("<form name='FormU' method='post' action='auth.php'><input type='hidden' name='user' value='"+Param+"'></form>"); document.FormU.submit(); //отослали на траницу проверки авторизации </script>
$cur_user =$_REQUEST["user"]; $login=$cur_user; $ds=ldap_connect("esrr-dc-02.esrr.oao.rzd"); // Необходимо указать корректный LDAP сервер ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); if ($ds) < $r=ldap_bind($ds, "логин@esrr.oao.rzd" ,"пароль"); // " не анонимная" привязка, $sr=ldap_search($ds, "OU=ESRR, DC=esrr, DC=oao, DC=rzd", "sAMAccountName=".mb_strtolower($login)); $info = ldap_get_entries($ds, $sr); for ($i=0; $i&lt;$info["count"]; $i++) < $fioful=iconv('utf-8', 'cp1251',$info[$i]["cn"][0]); $company=iconv('utf-8', 'cp1251',$info[$i]["company"][0]); $pref = explode("_", $cur_user); $upref = $pref[0]; $_SESSION['user_fio']=$fioful; // ФИО пользователя $_SESSION['user_d']=$login; // доменное имя пользователя $_SESSION['user_pred']=$company; // имя предприятия >// ЗДЕСЬ ПРОВЕРЯЕМ КАКОЕ-ЛИБО УСЛОВИЕ if ($stop == "1")< header ("Location: ./error.php"); >else < header ("Location: ./idx.php"); >// echo "Закрытие соединения"; ldap_close($ds); > else < echo "<h4>Невозможно подключиться к серверу LDAP</h4>"; >

Комментарии

6 комментариев к записи “PHP+Active Directory. Сквозная авторизация и получение информации о пользователе из домена.”

Читайте также:  Вывести только цифры python

Источник

Оцените статью