- Windows Authentication with Python and urllib2
- Edit after msander’s answer
- 2 Answers 2
- Authomatic: python библиотека для аутентификации и авторизации
- Регистрация приложения
- Определение конфигурации OAuth провайдеров
- Инициация базового объекта authomatic
- Создание представления
- pymssql windows authentication
- Send mail via Python logging in with Windows Authentication
- 1 Answer 1
- SMTP through Exchange using Integrated Windows Authentication (NTLM) using Python
- 3 Answers 3
Windows Authentication with Python and urllib2
I want to grab some data off a webpage that requires my windows username and password.
Is this supported by urllib2? I’ve found Python NTLM, but that requires me to put my username and password in. Is there any way to just grab the authentication information somehow (e.g. like IE does, or Firefox, if I changed the network.automatic-ntlm-auth.trusted-uris settings).
Edit after msander’s answer
So I’ve now got this:
which is pretty well ripped from socket_server.py (see here). But I get an error 400 — bad request. Does anyone have any further ideas?
2 Answers 2
Assuming you are writing your client code on Windows and need seamless NTLM authentication then you should read Mark Hammond’s Hooking in NTLM post from the python-win32 mailing list which essentially answers the same question. This points at the sspi example code included with the Python Win32 extensions (which are included with ActivePython and otherwise can be downloaded here).
There are several forms of authentication that web sites can use.
HTTP Authentication. This where the browser pops up a window for you to enter your username and password. There are two mechanisms: basic and digest. There is an «Authorization» Header that comes along with the page that tells a browser (or a program using urllib2) what to do.
In this case, you must configure your urlopener to provide the answers that the authorization header needs to see. You’ll need to build either an HTTPBasicAuthHandler or HTTPDigestAuthHandler.
AuthHandlers require a PasswordManager. This password manager could have a hard-coded username and password (very common) or it could be clever and work out your Windows password from some Windows API.
Application Authentication. This is where the web application directs you to a page with a form you fill in with a username and password. In this case, your Python program must use urllib2 to do a POST (a request with data) where the data is the form filled in properly. The reply to the post usually contains a cookie, which is what allows you further access. You don’t need to worry much about the cookie, urllib2 handles this automatically.
Authomatic: python библиотека для аутентификации и авторизации
Практически любое веб-приложение предоставляет возможность авторизации пользователя с использованием учетной записи пользователя, в каком либо из известных социальных сервисов.
Магия авторизации происходит строго по протоколу OAuth 1.0а и OAuth 2.0 и значительно упрощает жизнь и владельцу веб-приложения и самому пользователю.
Остается сущая мелочь, реализовать нужный протокол применительно к конкретному веб-приложению. Регистрация и вход в веб сервис TheOnlyPage с использованием учетных записей Facebook, Google, LinkedIn и Microsoft Live работают благодаря python библиотеке Authomatic.
Согласно документации Authomatic обладает следующими замечательными особенностями:
- Слабая связанность.
- Компактный, но мощный интерфейс
- Единственная, причем необязательная зависимость: библиотека python-openid
- CSRF защита
- Благодаря адаптерам нет привязки к конкретному фреймворку. Сразу из коробки поддерживается Django, Flask и Webapp2.
- Возможность включать новые появляющиеся протоколы авторизации и аутентификации
- Запросы к программному интерфейсу (API) провайдера — проще некуда.
- Поддержка асинхронных запросов
- В качестве бонуса javascript-библиотека
- Сразу из коробки поддержка:
- OAuth 1.0a провайдеров: Bitbucket, Flickr, Meetup, Plurk, Twitter, Tumblr, UbuntuOne,Vimeo, Xero, Xing and Yahoo
- OAuth 2.0 провайдеров: Behance, Bitly, Cosm, DeviantART, Facebook, Foursquare,GitHub, Google, LinkedIn, PayPal, Reddit, Viadeo, VK, WindowsLive, Yammer и Yandex.
- python-openid и OpenID основанного на Google App Engine
Вдобавок ко всему отмечается, что библиотека находится на очень раннем этапе создания, и практически не протестирована.
Несмотря на такое самокритичное заявление, если обратиться к демонстрационной страничке, можно убедиться что библиотека обеспечивает беспроблемную работу со всевозможными провайдерами OAuth 1.0a и OAuth 2.0.
Качественная документация даёт достаточно информации для использования библиотеки совместно с фреймворками: Django, Flask, Pyramid и Webapp2.
Проиллюстрируем работу с Authomatic на примере из реальной жизни. Для того чтобы зарегистрироваться / войти в веб-сервис TheOnlyPage посредством учетной записи Facebook, Google, LinkedIn и Microsoft Live достаточно кликнуть по соответствующей кнопке, на странице входа в сервис:
Процесс авторизации реализован при помощи библиотеки Authomatic. При этом TheOnlyPage работает на фреймворке Flask. Для того чтобы задействовать библиотеку Authomatic в связке с фреймворком Flask, при условии что библиотека уже присутствует в рабочем пространстве, нужно:
- Зарегистрировать свое приложение в каждом из OAuth-провайдеров.
- Добавить параметры OAuth-провайдеров в конфигурационный файл.
- Инициировать базовый объект authomatic параметрами, хранящимися в конфигурационном файле.
- Создать представление, которое выполнит запрос к провайдеру и получит от него результат.
Проделаем эти 4 нехитрых шага:
Регистрация приложения
У каждого провайдера свои особенности регистрации. Адреса регистрации приложения
Некоторые параметры, которые потребуется указать, у разных провайдеров могут отличаться, но среди остальных параметров обязательно присутствуют:
- адреса нашего сервиса, с которых разрешен редирект с запросом к провайдеру
- адрес, по которому провайдер возвращает пользователя к нашему сервису после предоставления доступа
- адрес, по которому провайдер возвращает пользователя к нашему сервису при отказе в предоставлении доступа
В случае использования библиотеки Authomatic в 1-м и 2-м случае удобно указать один и тот же адрес, так для соответствующих провайдеров будем использовать адреса:
Также на страничке регистрации приложения у провайдера, нам надо получить код пользователя и секретный ключ, в терминах различных провайдеров они соответственно называются:
код пользователя | секретный ключ | |
---|---|---|
App ID | App Secret | |
Client ID | Client secret | |
API Key | Secret Key | |
Microsoft Live | Client ID | Client secret |
Кроме того, в разделе регистрации приложения у провайдера, мы должны выяснить под каким названием фигурируют нужные нам данные. Например, адрес электронной почты пользователя обозначается:
для Facebook: email
для Google: email
для LinkedIn: r_emailaddress
для Microsoft Live: wl.emails
После того как приложение зарегистрировано во всех провайдерах, адреса редиректа указаны, код пользователя и секретный ключ получены, есть ясность как именуются данные применительно к каждому провайдеру, можно переходить к настройке конфигурационного файла.
Определение конфигурации OAuth провайдеров
В стандартный конфигурационный файл flask-приложения нужно добавить словарь содержащий параметры всех провайдеров:
Как видим каждому провайдеру ставится в соответствие словарь со следующими атрибутами:
class_ — входящий в состав библиотеки Authomatic класс, соответствующий очередному провайдеру;
consumer_key — код пользователя у очередного провайдера;
consumer_secret — секретный ключ очередного провайдера;
scope — список данных, которые предполагается запрашивать у очередного провайдера.
Предварительные установки сделаны.
Инициация базового объекта authomatic
Происходит очень просто, с указаним конфигурационных данных и секретной строки:
Создание представления
Осталось создать представление, которое:
- соответствует интернет адресу с которого осуществляется редирект запроса данных к провайдеру и получение данных от провайдера;
- осуществляет получение электронного адреса пользователя от oauth-провайдера;
- и, если этот пользователь зарегистрирован в системе – открывает ему доступ.
Основаня часть взаимодействия с oauth-провайдером сводится к одной строке:
при первоначальном заходе на адресу: authomatic.login осуществляет редирект на указанного провайдера и передачу необходимых параметров;
затем провайдер делает обратный редирект по тому же адресу и authomatic.login получает от провайдера требуемые данные.
Как видите совсем несложно. Основную часть времени занимает не программирование, а регистрация своего приложения в каждом из используемых провайдеров.
pymssql windows authentication
The pymssql module used to support windows authentication. Now it seems it does not. Though in some places it still shows that it should work. I have been unable to find a definitive answer to this problem, nor a solution. Most relevant link:
pymssql 1.0 supported it because it made use of and depended on the MS-provided DLL which was part of the SQL Server client stack. This stack was in charge of handling all of the NTLM negotiation and such. This meant, among other things that it was a Windows-only solution.
I can simulate many sorts of network environments so I have tried many different setups. I am trying to be able to use this script to connect to a remote MSSQL server using windows authentication. And this is the problem.
According to my research, including the links above, there are two ways to use windows authentication with the pymssql module that are supposed to work.
First Method: Using the current users credentials:
Second Method: Using a given users credentials:
The same goes for using the _mssql module.
NOTES:
- Python version: 2.7.8
- Version of pymssql I am using: 2.1.1
- Version of pymssql that used to support windows authentication: 1.x
- I have tested with (All 64 bit):
- windows 7 professional
- windows 7 home premium
- windows server 2012
- windows server 2012R2
Send mail via Python logging in with Windows Authentication
I’ve a conceptual doubt, I don’t know if it’s even possible.
Assume I log on a Windows equipment with an account (let’s call it AccountA from UserA). However, this account has access to the mail account (Outlook) of the UserA and another fictional user (UserX, without any password, you logg in thanks to Windows authentication), shared by UserA, UserB and UserC.
Can I send a mail from User A using the account of User X via Python? If so, how shall I do the log in?
Thanks in advance
1 Answer 1
A interesting feature with Windows Authentication is that is uses the well known Kerberos protocol under the hood. In a private environment, that means if a server trusts the Active Directory domain, you can pass the authentication of a client machine to that server provided the service is Kerberized, even if the server is a Linux or Unix box and is not a domain member.
It is mainly used for Web servers in corporate environment, but could be used for any kerberized service. Postfix for example is know to accept this kind of authentication.
If you want to access an external mail server, you will have to store the credential in plain text on the client machine, which is bad. An acceptable way would be to use a file only readable by the current user (live protection) in an encrypted folder (at rest protection).
SMTP through Exchange using Integrated Windows Authentication (NTLM) using Python
I want to use the credentials of the logged-in Windows user to authenticate an SMTP connection to an Exchange server using NTLM.
I’m aware of the python-ntlm module and the two patches that enable NTLM authentication for SMTP, however I want to use the current user’s security token and not have to supply a username and password.
3 Answers 3
Although the solution below only uses the Python Win32 extensions (the sspi example code included with the Python Win32 extensions was very helpful), the python-ntlm IMAP & SMTP patches mentioned in the question also served as useful guides.
Great answer but as an update for python 3
Python 2.7.x will fail on sending the NTLM Type 3 message due to the blank cmd specified:
code, response = smtp.docmd(«», ntlm_message)
This ends up sending the correct response back to the server, however it pre-pends a space due to the nature of docmd() calling putcmd().
which as a result takes the path of the else condition, thereby sending str(‘ ‘ + ntlm_message + CRLF) which results in (501, ‘Syntax error in parameters or arguments’) .
As such the fix is simply to send the NTLM message as the cmd.
code, response = smtp.docmd(ntlm_message)
A fix to the above answer was submitted, though who knows when it will be reviewed/accepted.