401 Client Error: Unauthorized

See original GitHub issue

I have checked all the issues, especially #207

I have registered the app: https://[tenant].sharepoint.com/_layouts/15/appinv.aspx

The app identifier has been successfully created.
Client Id:  	ID
Client Secret:  	TOKEN=
Title:  	PFS
App Domain:  	www.localhost.com
Redirect URI:  	https://www.localhost.com

I have given permissions: https://[tenant].sharepoint.com/_layouts/15/appinv.aspx XML:

<AppPermissionRequests AllowAppOnlyPolicy="true">
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl" />
</AppPermissionRequests>

But this code:

from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext

site_url = "https://[tenant].sharepoint.com/"
client_id = "ID"
client_secret = "TOKEN="

client_credentials = ClientCredential(client_id, client_secret)
ctx = ClientContext(site_url).with_credentials(client_credentials)
web = ctx.web
ctx.load(web)
ctx.execute_query()

print(web.properties['Url'])

Produces this error:

Traceback (most recent call last):
  File ".../lib/python3.6/site-packages/office365/runtime/client_request.py", line 75, in execute_query
    response.raise_for_status()
  File ".../lib/python3.6/site-packages/requests/models.py", line 943, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://[tenant].sharepoint.com/_api/Web

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "sharepoint.py", line 96, in <module>
    ctx.execute_query()
  File ".../lib/python3.6/site-packages/office365/runtime/client_runtime_context.py", line 138, in execute_query
    self.pending_request().execute_query()
  File ".../lib/python3.6/site-packages/office365/runtime/client_request.py", line 79, 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://[tenant].sharepoint.com/_api/Web')

If i use ctx = ClientContext(site_url).with_user_credentials(username, password) everything works fine.

Where do I go from here?

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
xibrizcommented, Jan 11, 2021

New week, new motivation 😃

I found this thread https://stackoverflow.com/questions/64025660/python-sharepoint-library-office365-rest-python-client-error-401-unauthorized

Install cmdlet if you don’t have it:

Install-Module -Name Microsoft.Online.SharePoint.PowerShell

Connect and run the command

Connect-SPOService -Url https://[tenant]-admin.sharepoint.com -Credential admin@domain.com
Set-SPOTenant -DisableCustomAppAuthentication $false

At first, I got the same error, but after a few minutes (5-10) the authorization worked without any other changes.

Note that my Office365 setup is only a few weeks old.

0reactions
vgremcommented, Jan 11, 2021

@xibriz good to know you get it fixed and thank you for sharing the details, I believe someone else will find this useful.

Indeed since:

For new tenants, apps using an ACS app-only access token is disabled by default. We recommend using the Azure AD app-only model which is modern and more secure. But you can change the behavior by running ā€˜set-spotenant -DisableCustomAppAuthentication $false’ (needs the latest SharePoint admin PowerShell).

setting DisableCustomAppAuthentication to $false should do the trick.

Regarding

I read that these client secrets is only valid for 12 months… is that true?

positive, according to Add-in secret expiration:

The add-in secret must be replaced every 12 months. For details, see Replace an expiring client secret in a SharePoint Add-in.

Although there is one trick available, for SharePoint Online app principal could be registered via Azure AD instead of AppRegNew.aspx page, this way app lifetime duration could be controlled on a more flexible level. image

Refer, for example, this post for more details.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to Fix a 401 Unauthorized Error? - GeeksforGeeks
The 401 Unauthorized Error is an HTTP status code error that represented the request sent by the client to the server that lacks...
Read more >
What is ā€œ401 Error Unauthorized Access" and How to Fix it?
The HTTP code ā€œ401 Unauthorized Accessā€ is a client-side error. It indicates that the website's server sends a ā€œWWW-Authenticateā€ header response back to...
Read more >
401 Unauthorized Error: What It Is and How to Fix It
The 401 Unauthorized Error is an HTTP response status code indicating that the client could not authenticate a request.
Read more >
401 Client Error: Unauthorized for url - python - Stack Overflow
It means you are sending wrong credentials please verify your credentials. – kvk30. Jan 29, 2018 at 9:57. 1.
Read more >
How to Quickly Fix the 401 Unauthorized Error (5 Methods)
The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for theĀ ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found