I'm trting to query twitter API v2 with elevated research access via tweepy, but it still gives me a 403 Forbidden.
client = tweepy.Client(
bearer_token=BEARER_TOKEN,
# consumer_key=CONSUMER_KEY,
# consumer_secret=CONSUMER_SECRET,
# access_token=OAUTH_ACCESS_TOKEN,
# access_token_secret=OAUTH_ACCESS_TOKEN_SECRET,
)
test = client.search_all_tweets(query="#something",
start_time = "2023-01-01")
print(test)
Response: Forbidden: 403 Forbidden When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.
I've tried all the combinations of the comented lines when created the client, notihg works.
What am I doing wrong?
No problem with normal acces endpoints and bearer_token param. However, can't nothing when using consumer_key/secret and acces_token(_secret) instead. Maybe this is the real issue?
Thank you in advance.
This table shows which account access or not
If you has free account (Essential or Elevated), you can't use search_all_tweets method. It is equivalent the GET /2/tweets/search/all API.
You can check which account has in your Developer Portal
https://developer.twitter.com/en/portal/products
In the three tabs (Essential, Elevated, and Academic Research),
Checked green item is your account.
But you can use recent 7 days search API by search_recent_tweets() even if free account.
That is equivalent with GET /2/tweets/search/recent
Related
I've purchased MS Office and they give me a space on onedrive.
Now I want to operate with that via ms graph API in my python console application (I used python onedrivesdk before but now it is said that it is deprecated).
I have registered an application and can see it via Azure AD on portal.azure.com.
Currently I'm trying to interact with my onedrive like this:
tenant_id = 'xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx'
authority = f'https://login.microsoftonline.com/{tenant_id}'
scope = 'https://graph.microsoft.com/.default'
app = msal.ConfidentialClientApplication(self.client_id, authority=authority, client_credential=self.client_secret)
result = app.acquire_token_silent(["https://graph.microsoft.com/.default"], account=None)
if not result:
logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
result = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
authToken = result['access_token']
#### Make a call to the graph API
graphResponse = requests.get('https://graph.microsoft.com/beta/me/drive',headers={'Authorization':f'Bearer {authToken}'})
if graphResponse.status_code != 200:
print('Error code: ', graphResponse.status_code)
print(graphResponse.text)
I successfully get an access token, but when I try to call /me/drive
I get status_code = 400 with
Current authenticated context is not valid for this request. This
occurs when a request is made to an endpoint that requires user
sign-in. For example, /me requires a signed-in user. Acquire a token
on behalf of a user to make requests to these endpoints. Use the
OAuth 2.0 authorization code flow for mobile and native apps and the
OAuth 2.0 implicit flow for single-page web apps
I've add permissions for the application on the portal via "API permission -> Add permission", but I'm unable to grant admin consent (In another ms account I have full fledged azure subscription where I'm an admin) because I'm not an admin. But who is admin of this account my MS office assigned to?
According to the code you provided, you use OAuth 2.0 client credentials flow to complete Azure AD auth and get access token. The access token required by service principal. We cannot use the access token to call /me/drive endpoint. We just can use the access token to call /users/<UserObjectIdOrUserPrincipalName}>/drive endpoint. For more details, please refer to the document
So if you want to call /me/drive endpoint, I suggest you use the OAuth 2.0 authorization code flow. Regarding how to implement it in your application, please refer to the sample.
Need to enumerate users, I'm using the auth0 client located here - https://github.com/auth0/auth0-python.
I've setup an example application, and made sure it has Client Credentials grant type. Via the example, trying to run the following . . . .
get_token = GetToken(domain)
token = get_token.client_credentials(non_interactive_client_id,
non_interactive_client_secret, 'https://{}/api/v2/'.format(domain))
mgmt_api_token = token['access_token']
auth0 = Auth0(domain, mgmt_api_token)
conns = auth0.connections.all()
return conns
However at .client_credentials, I'm failing with . ..
auth0.v3.exceptions.Auth0Error: 403: Client is not authorized to access "https://MY_DOMAIN/api/v2/". You might probably want to create a "client-grant" associated to this API.
There's a doc associated with the error, but it is 404.
The SDK is consuming the Management API via the client credentials grant using the non_interactive_client_id as the client id.
The error you are seeing is Auth0 telling you that that particular client id is not authorized to consume the API.
The Management API is a resource you can find in your Auth0 Dashboard under "APIs" (not sure but there was also a deep link such as manage.auth0.com/#/apis/management). In there there is a tab that should say something like "Non Interactive Clients" where you will see the list of all your clients and toggles to grant them access to the API.
After granting access to the API (and to the required scopes), your operation should work.
I'm trying to setup endpoints api (with google app engine, python), but I'm having some trouble getting user profile info. API is working, I can create entities through API Explorer on my localhost.
My goal is to allow user to register for my app by providing just an email, and authorizing the app to get the reset of the info from their profile. I have this endpoints method:
#User.method(http_method="POST",
auth_level=endpoints.AUTH_LEVEL.REQUIRED,
allowed_client_ids=[
endpoints.API_EXPLORER_CLIENT_ID
],
scopes=[
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/plus.me',
],
user_required=True,
request_fields=('email',),
response_fields=('id',),
name="register",
path="users")
def UserRegister(self, instance):
logging.info(os.getenv( 'HTTP_AUTHORIZATION' ))
# 'Beared __TOKEN__'
logging.info(endpoints.users_id_token._get_token(None))
# '__TOKEN__'
instance.put()
return instance
This works fine, I receive authorization token and user is created in datastore, but I can't figure out how to get the profile info. If I enter the token in OAuth2 API (through API Explorer):
POST https://www.googleapis.com/oauth2/v2/tokeninfo?access_token=__TOKEN__
I get token info with some data I need { "user_id": "__ID__", "verified_email": true, ...}, and if I use user_id in +API:
GET https://www.googleapis.com/plus/v1/people/__ID__
I can get the rest of the data I need (name, image, etc).
What do I need to do to achieve this in my UserRegister() method? I'd prefer to return just entity ID and do the rest of registration asynchronously, but that's another issue, I'll figure it out (; Just need some guidance how to call other endpoints from my code...
EDIT:
I've managed to figure out how to call other APIs (code on Gist), now only have one issue with Plus API:
I did some queries and eventually got anonymous quota error. Then I added key parameter and set it to WEB_CLIENT_ID or SERVICE_ACCOUNT:
WEB_CLIENT_ID is OAuth2 Client ID (type: Web Application) from console.developers.google.com/apis/credentials,
SERVICE_ACCOUNT is default App Engine service account - MY_APP#appspot.gserviceaccount.com...
and now I'm getting following error:
HttpError: <HttpError 400 when requesting https://www.googleapis.com/plus/v1/people/__VALID_USER_ID__?key=__WEB_CLIENT_ID__or__SERVICE_ACCOUNT__&alt=json returned "Bad Request">
When I use +API explorer I get results as expected:
REQUEST:
https://www.googleapis.com/plus/v1/people/__VALID_USER_ID__?key={YOUR_API_KEY}
RESPONSE:
200 OK + json data for user...
Anyone knows why is this happening?
Why am I getting BadRequest response?
Problem with BadRequest was that I didn't send authorization token... I did try to send it as access_token, but seams like +api docs are outdated - it should be oauth_token. When I included this parameter issue was resolved:
build('plus', 'v1').people().get(userId=user_id, key=SERVICE_ACCOUNT, oauth_token=token).execute()
HINT: Use http://localhost:8001/_ah/api/discovery/v1/apis/, and discoveryRestUrl property it has to see real properties of your API - this is where I found the answer.
oauth_token can be obtained like this:
token = os.getenv('HTTP_AUTHORIZATION').split(" ")[1]
# or like in my question:
token = endpoints.users_id_token._get_token(None)
I'd suggest HTTP_AUTHORIZATION variable, because users_id_token docs state that it's a:
Utility library for reading user information from an id_token.
This is an experimental library that can temporarily be used to extract
a user from an id_token. The functionality provided by this library
will be provided elsewhere in the future.
How to call other API Endpoints?
This is also an answer to my first question:
from googleapiclient.discovery import build
service = build('plus', 'v1')
request = service.people().get(userId=user_id, key=SERVICE_ACCOUNT, oauth_token=token)
response = request.execute()
data = dict(self.response.POST)
Code that worked for me is here.
NOTE: WEB_CLIENT_ID obtained from https://console.developers.google.com/apis/credentials (OAuth2 Client ID of type Web Application) will NOT work in this case. I had to use SERVICE_ACCOUNT - I didn't try to generate one through console, default service account I got from App Engine worked fine.
...things are much clearer now that I got this working. Hope it will help someone else (;
Any tips on python oauth2 and facebook.
It seems there are little information since Facebook updated to OAuth2.
Is there anyway the existing Twitter library can be used to suite the facebook authentication?
import oauth2 as oauth
# Create your consumer with the proper key/secret.
consumer = oauth.Consumer(key="your-twitter-consumer-key",
secret="your-twitter-consumer-secret")
# Request token URL for Twitter.
request_token_url = "http://twitter.com/oauth/request_token"
# Create our client.
client = oauth.Client(consumer)
# The OAuth Client request works just like httplib2 for the most part.
resp, content = client.request(request_token_url, "GET")
print resp
print content
If your looking for readily available Django apps to integrate with your project, check out the authentication packages. Most of them that provide Facebook authentication have been updated to support the OAuth 2 protocol for some time already.
If, on the other hand, you'd like to work with a provider through an OAuth 2 library directly, take a look at python-oauth2--there's a lengthy example of how you can integrate it with Django's authentication immediately in the README.
There is an awesome project called Fandjango and Facepy. Simply, you don't even have to know or even worry about OAuth protocols anymore.
If you want all the user's details or are integrating more of Facebook's graph api, you should have a look at:
https://github.com/tschellenbach/Django-facebook
For a demo of how slick it is:
http://www.fashiolista.com/intro_wide/
Features (Copied from github)
Access the Facebook API, from:
Your website (Using javascript OAuth)
Facebook canvas pages (For building facebook applications)
Mobile (Or any other flow giving you a valid access token)
Django User Registration (Convert Facebook user data into a user model)
Use Facebook data to register a user with your Django app. Facebook connect using the open graph API.
Facebook FQL access
OAuth 2.0 compliant
Includes Open Facebook (stable and tested python client to the graph API)
I'm new to FB app development. Once the user authorize my app, facebook does the following request
http://www.example.com/response#access_token=...&expires_in=3600
Now my python do not see the part after the '#'. How do i get the part, or am i doing something wrong?
You cannot use this. That is part of client side auth. URI fragments (the stuff after the #) are never sent to the server by the browser. You need to look up server side auth.
Short answer: you need to fill in YOUR_URL in https://www.facebook.com/dialog/oauth?
client_id=YOUR_APP_ID&redirect_uri=YOUR_URL, next the facebook app (in python) needs to filter the return URL and yank out the access_token in the callback.
For more information, drop by https://apps.facebook.com/fileglu/technical - i am using facebook's access_token and dropbox's access_token to enable dropbox access inside Facebook App.
Have hooks for Google Oauth 2.0, anyone requires google docs access within Facebook?