Office365-REST-Python-Client icon indicating copy to clipboard operation
Office365-REST-Python-Client copied to clipboard

Cookie based auth

Open jben-hun opened this issue 2 years ago • 1 comments

Hi, thanks for the beautiful lib!

Is it possible to authenticate using FedAuth or rtFA cookies exported from a browser for development/prototyping use cases?

jben-hun avatar Dec 12 '23 10:12 jben-hun

Yes, you can if you want. Here's example code:

from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.authentication_context import AuthenticationContext

# Patch the library to support authentication by Cookie
def authentication_context_with_cookie(self, cookies):
    def _authenticate(request):
        if self._cached_cookies is None:
            self._cached_cookies = cookies
        cookie_header_value = "; ".join(
            [
                "=".join([key, str(val)])
                for key, val in self._cached_cookies.items()
            ]
        )
        request.set_header("Cookie", cookie_header_value)
        
    self._authenticate = _authenticate
    return self

def client_context_with_cookie(self, cookies):
    self.authentication_context.with_cookie(cookies)
    return self

setattr(AuthenticationContext, 'with_cookie', authentication_context_with_cookie)
setattr(ClientContext, 'with_cookie', client_context_with_cookie)
setattr(AuthenticationContext, '_cached_cookies', None)
# end of library patching


authCookie = {
    "rtFa": rtFa,
    "FedAuth": FedAuth,
   }
ctx = ClientContext(site_url).with_cookie(authCookie)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print(web.properties)

cvandeplas avatar Feb 08 '25 06:02 cvandeplas