0
votes

I am trying to use the App-only flow for Share point.

First, I have created a new app client-id and secret with this URL https://mydomain.sharepoint.com/sites/sample/_layouts/15/appregnew.aspx.

Then I went to the URL https://mydomain.sharepoint.com/sites/sample/_layouts/15/appinv.aspx to give permissions to this app with the following xml.

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

and clicked on trust it.

The code that I am using :

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

site_url = 'https://mydomain.sharepoint.com/sites/sample/'
app_principal = {
  'client_id': '.....-..',
  'client_secret': '......=',
}

context_auth = AuthenticationContext(url=site_url)
context_auth.acquire_token_for_app(client_id=app_principal['client_id'], 
client_secret=app_principal['client_secret'])

ctx = ClientContext(site_url, context_auth)
web=ctx.web
ctx.load(web)
ctx.execute_query()
if len(result) > 0:
    print("Folder has been found: {0}".format(result[0].properties["Name"]))

But it throws the following error : Traceback (most recent call last): File "client.py", line 16, in <module> ctx.execute_query() File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\office365\runtime\client_runtime_context.py", line 140, in execute_query self.pending_request().execute_query() File "C:\Users\AppData\Local\Programs\Python\Python37\lib\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://mydomain.sharepoint.com/sites/sample/_api/Web')

Need help.

1
I have this exact same issue, were you able to solve it? - Erfan
@Erfan I instead chose the other way of implementation which is, using certificates and it worked but it's a different approach altogether. Somehow client_id and secret was not working even after following the documented steps. - Vishal Tyagi

1 Answers

2
votes

I follow your steps,but I could not reproduce your issue. enter image description here

If your office365 tenant is created recently,you could try to run below command.

Set-SPOTenant -DisableCustomAppAuthentication $false

Tip:You need to update the SharePoint Online managed shell to the latest version.

Updated: enter image description here