Connect Python to SharePoint List - python-3.x

I am trying to access a SharePoint List with OAuth2 security and am experiencing issues with gaining access.
Error:
Cannot get security assertion for user [user]#[company].com from federation-sts.[company].com/adfs/services/trust/2005/…
An error occurred while retrieving auth cookies from ts.[company].com/_forms/default.aspx?wa=wsignin1.0
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
url = 'https://company.sharepoint.com'
username = 'user123#company.com'
password = 'password'
listname = 'Test List'
ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(username, password):
ctx = ClientContext(url, ctx_auth)
web = ctx.web
sp_list = ctx.web.lists.get_by_title(listname)
items = sp_list.get_items()
ctx.load(items)
ctx.execute_query()
else:
print(ctx_auth.get_last_error())
Try #2 with SharePlum:
from shareplum import Site
from shareplum import Office365
authcookie = Office365('https://ts.company.com', username='user', password='pw').GetCookies()
site = Site('https://ts.company.com/sites/SiteName/', authcookie=authcookie)
SharePlum error (I know my credentials are correct)
Exception: ('Error authenticating against Office 365. Error from Office 365:', 'AADSTS50126: Error validating credentials due to invalid username or password.

I tried it with below code on my SPO environment, it works well:
tenant_url= "https://abc.sharepoint.com"
site_url="https://abc.sharepoint.com/sites/A"
listname = 'Test List'
ctx_auth = AuthenticationContext(tenant_url)
if ctx_auth.acquire_token_for_user("x#abc.onmicrosoft.com","xxxx"):
ctx = ClientContext(site_url, ctx_auth)
web = ctx.web
sp_list = ctx.web.lists.get_by_title('kkkk')
items = sp_list.get_items()
ctx.load(items)
ctx.execute_query()
print(items)
else:
print(ctx_auth.get_last_error())
Could you please confirm that the username/password is correct? And You can also have a try another python library for Sp connection:
SharePlum: Python + SharePoint

Related

often redirected to login page rather than authorization page

import random
import urllib.parse as urllibparse
import spotipy
from spotipy.oauth2 import SpotifyOAuth
# credentials
Client_Id = <CLIENT_ID>
Client_Secret = <CLIENT_SECRET>
redirect_uri = 'http://localhost:5500/'
scope = "playlist-modify-private playlist-modify-public"
response_type = 'code'
username = <USERNAME>
randomNum =str(random.getrandbits(128))
hash = int(randomNum,36)
state = hex(hash)
spotifyToken = SpotifyOAuth(Client_Id,Client_Secret,redirect_uri,state,scope)
auth_url = spotifyToken.get_authorize_url()
print(auth_url)
spotifyObject = spotipy.Spotify(auth_manager=spotifyToken)
print(spotifyObject)
playlistName = "random"
playlistDescription = "just to check"
spotifyObject.user_playlist_create(user=username,name=playlistName,public=True,description=playlistDescription)
suggestions required
often redirected to login page rather than authorization page pls suggest some solution to resolve this problem or suggest any other way.

How to use the Google Sign In access token instead of authorization code for getting the data from the Google Search Console?

I want to access the listed websites data in the Google Search Console using the Google Sign-In access_token (that one can get as the response when using Google Sign-In).
But, the thing is I can access that data only by using the authorization_code that can be copied from the OAuth2-Consent screen by going to the generated authorize_url and signing in using the registered Google account.
Here's the minimum reproducible version of the code:
from oauth2client.client import OAuth2WebServerFlow
import httplib2
from apiclient.discovery import build
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters.readonly'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print ('Go to the following link in your browser: ' + authorize_url)
code = input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
http = httplib2.Http()
http = credentials.authorize(http)
webmasters_service = build('webmasters', 'v3', http=http)
def get_property_list(webmasters_service):
'''
Get a list of validated properties from GSC
'''
site_list = webmasters_service.sites().list().execute()
# Filter for verified websites
verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
if s['permissionLevel'] != 'siteUnverifiedUser'
and s['siteUrl'][:4] == 'http']
return verified_sites_urls
print({"available_websites": get_property_list(webmasters_service)})
Consider that I'll be provided with the Google Sign-In access-token as the request-parameter from another server which has implemented Google Sign-In feature.
So, again my question is how can I access the same data using that token instead of manually getting the auth_code from the OAuth2 consent screen ?
I have followed the documentation shared by DaImTo in the comments above. And modified the code as shown below:
from oauth2client.client import OAuth2WebServerFlow
import httplib2
from apiclient.discovery import build
from oauth2client import tools, file
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters.readonly'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
# Acquire and store oauth token.
storage = file.Storage('token.json')
credentials = storage.get()
if credentials is None or credentials.invalid:
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
credentials = tools.run_flow(flow, storage)
http = httplib2.Http()
http = credentials.authorize(http)
webmasters_service = build('webmasters', 'v3', http=http)
def get_property_list(webmasters_service):
'''
Get a list of validated properties from GSC
'''
site_list = webmasters_service.sites().list().execute()
# Filter for verified websites
verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
if s['permissionLevel'] != 'siteUnverifiedUser'
and s['siteUrl'][:4] == 'http']
return verified_sites_urls
print({"available_websites": get_property_list(webmasters_service)})
It's working fine now, without any manual interaction for copying and pasting the authorization_code from the OAuth2-Consent screen.

Issues using shareplum to access sharepoint

I'm trying to access a sharepoint site using Shareplum.
from shareplum import Site
from shareplum import Office365
authcookie = Office365('https://my.sharepoint.com', username='username#domain.edu', password='password').GetCookies()
site = Site('https://my.sharepoint.com/personal/.../_layouts/15/onedrive.aspx', authcookie=authcookie)
sp_list = site.List('list items')
data = sp_list.GetListItems('All Items', rowlimit=200)
However, I get the following error when I try to run this script.
Exception: ('ERROR:', 500, '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>Exception of type \'Microsoft.SharePoint.SoapServer.SoapServerException\' was thrown.</faultstring><detail><errorstring xmlns="http://schemas.microsoft.com/sharepoint/soap/">\r\n List does not exist.\r\n The page you selected contains a list that does not exist. It may have been deleted by another user.\r\n </errorstring><errorcode xmlns="http://schemas.microsoft.com/sharepoint/soap/">0x82000006</errorcode></detail></soap:Fault></soap:Body></soap:Envelope>')
Any ideas of what is going on?
The error shows that the specified list does not exist. From the site url, i understand you want to retrieval list items from personal site (onedrive). Please take a reference of below code, it works well here:
from shareplum import Site
from shareplum import Office365
from shareplum.site import Version
from config import config
# get data from configuration
username = config['sp_user']
password = config['sp_password']
authcookie = Office365('https://xxx-my.sharepoint.com', username=username, password=password).GetCookies()
site = Site('https://xxx-my.sharepoint.com/personal/aaa_xxx_onmicrosoft_com',version=Version.v365, authcookie=authcookie)
sp_list = site.List('Documents')
data = sp_list.GetListItems('All',row_limit=10)
print(data)

How to get access to a webpage with multi-factor authentication using python

I'm trying to access newclasses.nyu.edu to create a program that involves scraping the website but I need to first login with my student details and then enable MFA from my phone. How can I do this?
I have been able to get the user login details and store it in a dictionary but for some reason it shows invalid password
#Getting user_data
def login():
login_data = {}
NetID = input("Enter your NetID")
password = input("Enter your password")
login_data['j_username'] = NetID
login_data['j_password'] = password
login_data['_eventId_proceed'] = ''
return login_data
with requests.Session() as s: #Maintain a session
url = "https://newclasses.nyu.edu"
request = s.get(url) #Getting access to the site
#soup = BeautifulSoup(request.content, 'html5lib') #Scraping the site
login_data = login()
print(login_data)
request = s.get(url, data = login_data)
print(request.content)
This code prints out the webpage showing an invalid password but what I want is to be able to login and activate the MFA and get access to the site

How to show validation error for inactive user with some response code

I am trying to build custom user model in django-rest-framework. The problem which i am facing is how should i show the custom message with response code when the user is not activate.
Currently if the user provided the correct credentials but the account is not active then he is throwing error response code 400 with the validation error. Here is my code which I am using for the login validation.
class TokenAuthSerializer(serializers.Serializer):
email = serializers.CharField()
password = serializers.CharField(
style = {'input_type':'password'},
trim_whitespace = False
)
def validate(self,attrs):
email = attrs.get('email')
password = attrs.get('password')
user = authenticate(
request= self.context.get('request'),
email = email,
password = password
)
if not user:
msg = _('Unable to authenticate with given credentials')
raise serializers.ValidationError(msg, code = 'authorization')
attrs['user'] = user
return attrs
In views:
class CreateTokenAuthorization(ObtainAuthToken):
serializer_class = TokenAuthSerializer
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
How to override this method to get the proper response code for the user is not active. Thank you for looking over it.

Resources