Python requests - how to perform SAML SSO login (to login.microsoft.com for example)?

Viewed 834

First of all, I googled this question but found some generic explanations which didn't provide me with good understanding how to do things.

Second - I'm a valid system user (not admin) and have access to the data. I.e. I have valid user credentials and may download file manually but for small automation I would like to have it downloaded by python script from my PC.

The download itself is simple, the only thing - I need to provide a valid session id cookie with request. I.e. finally I need to get this cookie by easiest way.

If my understaning is right in terms of SAML I'm a User Agent and want to download a file from Sevice Provider which need to authenticate me with Identity Provider (Microsoft). Usually I do it via browser and now I'm able to emulate it with help of PySide6 (QWebEngineView). I load target URL first in QWebEngineView. Actually it is a small embedded web-browser, it redirects me to login.microsoft.com, asks credentials and then redirects me back to Service Provider site and sets session id cookie. Then I'm able to use this cookie with my requests. It works but I would like to get rid of GUI (PySide) if possible.

I decided to replicate a flow that browser does and failed almost at the begining. What happens:

  1. I'm requesting a file from my Service Provider side with usual get request.
  2. Service provider replies with HTML page (instead of target file) as I'm not authenticated.
  3. This HTML page contains Java script triggered by onPageLoad event - this java script simply redirects browswer to login.microsoft.com (long URL with some parameters).
  4. Next request with this long URL for login.microsoft.com ends with "302 Moved Temporarily" with the same URL in "Location" header. And when I go with this URL it again gives me 302 with the same URL. With the same scenario browswer gets only two redirections and finally receives an URL of web page with login/password request from microsoft.com.

I understand that I should put some more headers/cookies when I go again with URL provided in "Location" header of 302 response. But... I have no idea what login.microsoft.com expects here. So my question is - is there any source where this message flow is described? Or maybe someone did it already and may give me advice how to proceed?

I found some SAML-related libraries for python but I see there quite complex configuration with x509 certificates and more stuff - it looks like they are more targeted for implementation on Service Provider side, not for external login.

0 Answers
Related