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

401 response using token

Open SteveScott opened this issue 1 year ago • 3 comments

I am uploading to sharepoint using a token. I am successfully receiving a response and creating a TokenResponse that contains a proper token.

I am also creating a ClientContext object with this token:

def get_ctx() -> ClientContext:
    ctx = ClientContext(settings['url']).with_access_token(get_token)
    return ctx

However, when I execute a query, it says I am not authenticated with a 401 error.

def upload_from_session(ctx: ClientContext, local_path,endpoint_url):
    target_url = endpoint_url
    target_folder = ctx.web.get_folder_by_server_relative_url(target_url)
    size_chunk = 262_144
    with open(local_path, "rb") as payload:
        uploaded_file = target_folder.files.create_upload_session(
            payload, size_chunk, print_upload_progress).execute_query()

Yet context has a token? What could be the issue?

SteveScott avatar Jan 26 '24 16:01 SteveScott

This is my error:

  File "\\local\path\sharepoint_upload.py", line 159, in upload_from_session
    payload, size_chunk, print_upload_progress).execute_query()
                                                ^^^^^^^^^^^^^^^
  File "C:\Users\me\Anaconda3\envs\my_folder\Lib\site-packages\office365\runtime\client_object.py", line 52, in execute_query
    self.context.execute_query()
  File "C:\Users\me\Anaconda3\envs\my_folder\Lib\site-packages\office365\runtime\client_runtime_context.py", line 191, in execute_query
    self.pending_request().execute_query(qry)
  File "C:\Users\me\Anaconda3\envs\my_folder\Lib\site-packages\office365\runtime\client_request.py", line 42, in execute_query
    raise ClientRequestException(*e.args, response=e.response)
office365.runtime.client_request_exception.ClientRequestException: (None, None, "401 Client Error: Unauthorized for url: https://my-domain.com/sites/my-site/_api/Web/getFolderByServerRelativeUrl('folder%subfolder%2F')/Files/add(overwrite=true,url='test_file.csv')")

SteveScott avatar Jan 26 '24 17:01 SteveScott

It is interesting to note that I do not get a 401 error when calling ctx.web.get_folder_by_server_relative_url(target_url). 401 error means unauthenticated, but is it possible I do not have permission? If I did not have permission I would expect a 403 error.

SteveScott avatar Jan 26 '24 17:01 SteveScott

I am even getting a 401 error when I try execute_request_direct: This is my old code, just added the "Authorization" header

def upload_data(ctx : ClientContext, endpoint_url : str, payload, token=None):
    request = RequestOptions(endpoint_url)
    request.set_header('content-length', str(len(payload)))
    request.set_header('content-type', "application/json;odata=verbose")
    if token is not None:
        request.set_header('Authorization', "Bearer " + token)
        #print(f"this is my token : {token}")
    request.data = payload
    request.proxy = 'http://myproxy.mydomain'
    request.method=HttpMethod.Post
    response = ctx.pending_request().execute_request_direct(request)

    try:
        assert response.status_code == 200
    except AssertionError as e:
        logging.error(f'response was not 200, {response.text}')
        raise requests.exceptions.HTTPError({f"{response.status_code}, {response.text}"})
    return response

SteveScott avatar Jan 26 '24 20:01 SteveScott