简体   繁体   中英

SharePoint Online access token from Python

Any help is much appreciated! I have tried so many libraries and ways of doing this, nothing seems to work. I'm inexperienced with REST APIs and accessing SharePoint using them. I have tried out various code samples that use Python requests, office365-REST-Python-Client, HttpNtlmAuth, OAuth2, rauth, etc.

Our SharePoint administrator set up a SharePoint AddIn for me to access my site data. Said it wouldn't be my user name and password in the API, but using a client, and first getting the access token, then making the API calls.

The frustrating thing is a SharePoint admin set up the calls in Postman, and the API request calls to get the access token and also get the site file and folder data I want work fine there. I can even create my own API requests in Postman using the same parameters she created and it works great. But trying to do this in my Python app has given my all kinds of errors and issues. For now, I am just trying to retrieve my access token in Python.

Here is my current code and error. All text inside of brackets and ALL CAPS are non-literal/obscured for obvious reasons since I am posting this online. The Error is:

File "[MY LOCAL DRIVE LOCATION...]\\venv\\lib\\site-packages\\office365\\runtime\\auth\\authentication_context.py", line 45, in acquire_token_for_app raise ValueError('Acquire token failed: {0}'.format(self.provider.error)) ValueError: Acquire token failed: None

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

class SharepointService:

        site_url = 'https://accounts.accesscontrol.windows.net/[TENANT ID the SP ADMIN GAVE ME]/tokens/OAuth/2?content'
        client_id = '[THE CLIENT ID THE SP ADMIN GAVE ME]'
        client_secret = '[THE CLIENT SECRET THE SP ADMIN GAVE ME]'

        app_principal = {'client_id': client_id, 'client_secret': client_secret}

        context_auth = AuthenticationContext(url=site_url)

        token = context_auth.acquire_token_for_app(client_id=app_principal['client_id'], client_secret=app_principal['client_secret'])
        print(token)

        ctx = ClientContext(site_url, context_auth)

        web = ctx.web
        ctx.load(web)
        ctx.execute_query()
        print("Web site title: {0}".format(web.properties['Title']))


It seems that you should change your site_url to the site which you want to access.

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

site_url = 'https://contoso.sharepoint.com/sites/dev'
app_principal = {
  'client_id': 'e53634cb-xxxx-4e3a-8557-026a9393e215',
  'client_secret': 'SKjZHU4Ubr2BTouPsiXXtz9YeHU/yBww/xXxanq1I2k=',
}

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()
print("Web site title: {0}".format(web.properties['Title']))

Test result: 在此处输入图片说明

path('api-auth/',include ('rest_framework.urls',namespace='rest_framework')), path('api/', include('djoser.urls')), ####urls.py
from rest_framework.decorators import api_view
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
##vies.py
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
###serializers.py

 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.AllowAny', "rest_framework.permissions.DjangoModelPermissions", ##settings.py

This is still the top Google result for this error.

It's caused by two things:

  • Azure failing to authenticate your Sharepoint add-in for some reason.
  • You're running a version of office365-rest-python-client < 2.3.0 - before this version, the failure was silent

This line (raise_for_status) now prints the azure auth failure: https://github.com/vgrem/Office365-REST-Python-Client/blob/2.3.0/office365/runtime/auth/providers/acs_token_provider.py#L69

In my case the auth failure was due to the keys expiring after a year.

You can refresh them as so: https://medium.com/@cecildt/renewing-sharepoint-online-provider-add-ins-client-secret-ba2828a49e7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM