Skip to content
Advertisement

Sharepoint file storage give password expired reason through password not expired using python

Unable to upload the file in SharePoint, since yesterday the code is working fine used stored file in Sharepoint now am getting the below error:

Exception: (‘Error authenticating against Office 365. Error from Office 365:’, ‘AADSTS50055: The password is expired.’)

The same thing happened for the other two accounts even. The function uploadMeta_file(filepath_meta) to call Sharepoint

File “c:UsersDesktopworksamplecookiepopup-kana-api.venvlibsite-packagesshareplumoffice365.py”, line 80, in get_security_token raise Exception(‘Error authenticating against Office 365. Error from Office 365:’, message[0].text) Exception: (‘Error authenticating against Office 365. Error from Office 365:’, ‘AADSTS50055: The password is expired.’)

import requests
import jsonpath
import os, requests, uuid, json
import pandas as pd
from shareplum import Office365
import xlsxwriter
from shareplum import Site
from datetime import datetime 
import logging 



def kana_api():
    
    writer.save()
    filepath_meta ="kana1_input.xlsx"
    uploadMeta_file(filepath_meta)
    


    #metadata file
def uploadMeta_file(filepath_meta): 


# working with crentials
    username = "myid
    password = "mypassword"
    site_name = "AFFinance"
    base_path = "validpath"
    doc_library ="validlib"
        
    
    file_name = filepath_meta
    # Obtain auth cookie
    authcookie = Office365(base_path, username=username, password=password).GetCookies()
    session = requests.Session()    
    session.cookies = authcookie
    session.headers.update({'user-agent': 'python_bite/v1'})
    session.headers.update({'accept': 'application/json;odata=verbose'})

    session.headers.update({'X-RequestDigest': "FormDigestValue"})
    response = session.post( url=base_path + "/sites/" + site_name + "/_api/web/GetFolderByServerRelativeUrl('" + doc_library + "')/Files/add(url='a.txt',overwrite=true)",
                                data="")
    logging.info(response)
    session.headers.update({'X-RequestDigest': response.headers['X-RequestDigest']})
    # perform the actual upload
    with open( file_name, 'rb') as file_input:
        try: 
            response = session.post( 
                url=base_path + "/sites/" + site_name + "/_api/web/GetFolderByServerRelativeUrl('" + doc_library  + "')/Files/add(url='" 
                + file_name + "',overwrite=true)",
                data=file_input)
            logging.info("Meta File uploaded")
        except Exception as err: 
            logging.info("Some error occurred....")
    


if __name__== '__main__':
    kana_api()

Advertisement

Answer

Like you mentioned there is MFA enabled for your account. Looks like you have not handled the same in your application.

There 2 ways to go about this.

  1. Provide Interactive logon UI for handling the MFA.

  2. Create a service account which has the MFA disabled. Thereby using this account to access the Sharepoint Online, you will not encounter the above issue.

  3. Using App Only Authentication

What are Sharepoint app only ?

App only authentication – will not require user credentials but you can get the data by authenticating the App. And Also, app authentication will indirectly bypass MFA (App only authentication are not subjected to MFA).

More information : https://learn.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs

I was reading through the Shareplum Tutorials – Unfortunately, but could not get the way to do the App Only Authentication. But you could double check at your end.

If your goal is to use python, you can also use the below library :

https://pypi.org/project/Office365-REST-Python-Client/#Working-with-SharePoint-API

To perform the app only authentication :

client_credentials = ClientCredential('{client_id}'),'{client_secret}')
ctx = ClientContext('{url}').with_credentials(client_credentials)

But yes, you will have reform your code to perform the required action to make use of the above library.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement