How can I use Python Keyring in conjunction with Box API OAuth2? - python

I'm pretty new to Python and programming and I am trying to figure out how to automate the box.com authentication process and it's kicking my butt. Any help would be appreciated!
I have this code below, which obviously wasn't mine but came from a tutorial. I am trying to figure out the
keyring.get_password('Box_Auth', 'mybox#box.com')
I'm thinking the mybox#box.com is my redirect URI? But I'm not sure what it is looking for when it asks for the Box_Auth.
Here is the full code
"""An example of Box authentication with external store"""
import keyring
from boxsdk import OAuth2
from boxsdk import Client
CLIENT_ID = ''
CLIENT_SECRET = ''
def read_tokens():
"""Reads authorisation tokens from keyring"""
# Use keyring to read the tokens
auth_token = keyring.get_password('Box_Auth', 'mybox#box.com')
refresh_token = keyring.get_password('Box_Refresh', 'mybox#box.com')
return auth_token, refresh_token
def store_tokens(access_token, refresh_token):
"""Callback function when Box SDK refreshes tokens"""
# Use keyring to store the tokens
keyring.set_password('Box_Auth', 'mybox#box.com', access_token)
keyring.set_password('Box_Refresh', 'mybox#box.com', refresh_token)
def main():
"""Authentication against Box Example"""
# Retrieve tokens from secure store
access_token, refresh_token = read_tokens()
# Set up authorisation using the tokens we've retrieved
oauth = OAuth2(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
access_token=access_token,
refresh_token=refresh_token,
store_tokens=store_tokens,
)
# Create the SDK client
client = Client(oauth)
# Get current user details and display
current_user = client.user(user_id='me').get()
print('Box User:', current_user.name)
Again, I would really appreciate any help!

I was having the exact same issue.
You will need an access token and a refresh token.
Read here how to generate those.

Related

How to get Microsoft Graph API token to read mails

I'm trying to retrieve mails from my organization's mailbox, and I can do that via Graph Explorer. However, when I use the same information that I used in Graph Explorer, the generated token returns an error stating '/me request is only valid with delegated authentication flow.' in me/messages endpoint.
So, how can I generate the acceptable token for the /me endpoint?
An example python code or example Postman request would be amazing.
It sounds like the endpoint you're using in Graph Explorer is something like this
https://graph.microsoft.com/v1.0/me/messages
/me is referring to the user signed into Graph Explorer. If you want to read another user's messages you would use
https://graph.microsoft.com/v1.0/users/user#domain.com/messages
When connecting to Graph API as an application with no user interaction, you can never use /me endpoints, as there's no user logged in.
Reference
https://learn.microsoft.com/en-us/graph/api/user-list-messages?view=graph-rest-1.0
Python example to list messages
import requests
def get_messages(access_token, user):
request_url = f"https://graph.microsoft.com/v1.0/users/{user}/messages"
request_headers = {
"Authorization": "Bearer " + access_token
}
result = requests.get(url = request_url, headers = request_headers)
return(result)
msgs = get_messages(access_token = token['access_token'], user = "userPrincipalName#domain.com")
print(msgs.content)
Additional example of obtaining a token, using an app registration and client secret
import msal
def get_token_with_client_secret(client_id, client_secret, tenant_id):
# This function is to obtain a bearer token using the client credentials flow, with a client secret instead of a certificate
# https://docs.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS#client-credentials-provider
app = msal.ConfidentialClientApplication(
client_id = client_id,
client_credential = client_secret,
authority = f"https://login.microsoftonline.com/{tenant_id}")
scopes = ["https://graph.microsoft.com/.default"]
token = app.acquire_token_for_client(scopes = scopes)
return(token)

Tweepy API v2 Authentication

How can I test the Tweepy authentication using API v2?
My code below fails to post due to authentication however, is there any other way to test the authentication without invoking posting a Tweet (client.create_tweet) ?
import tweepy
bearer_token = "hidden"
consumer_key = "hidden"
consumer_secret = "hidden"
access_token = "hidden"
access_token_secret = "hidden"
client = tweepy.Client(bearer_token=bearer_token)
client = tweepy.Client(
consumer_key=consumer_key,
consumer_secret=consumer_secret,
access_token=access_token,
access_token_secret=access_token_secret
)
client.create_tweet(text="My first tweet")
You can use any of the methods listed in the documentation here.
I would suggest you to use some read method like get_user:
user = client.get_user('twitter')
print(user.name)
About your authentication itself, the problem is that you have to choose between:
Using the bearer token of your application to get an OAuth 2 "App-Only" authentication. You will have, basically, the same possibilies as an unregistered user on the website.
Using an account's tokens to get an OAuth 1.0a "User Context" authentication. You will then be able to act in the behalf of the user who possesses the tokens that you are using.
But you are trying to do both successively.
I put the bearer token with the other parameters in tweepy.Client, it's not separated and works every time:
import tweepy
client = tweepy.Client(bearer_token="YOUR_BEARER_KEY",
consumer_key="YOUR_CONSUMER_KEY",
consumer_secret="YOUR_CONSUMER_SECRET",
access_token="YOUR_ACCESS_TOKEN",
access_token_secret="YOUR_ACCESS_TOKEN_SECRET")
You can also add wait_on_rate_limit=True to limit your rates in case your not handling them properly.
For a simple test similar to Mickaƫl's Answer which prints a twitter username to its respective id:
user_get = client.get_user(username='a_twitter_username_here')
user_id = user_get.data.id
print(user_id)
If this does not work then try regenerating your keys and tokens if you can.
This method does not need elevated access.

Generate access token by google login using oauth2

My front end in Angular JS.
It sends me google token after user logs in with gmail
In backend I verify the token and extract information from it as below
#csrf_exempt
def check(request):
CLIENT_ID = 'xxxxx'
try:
json_data = json.loads(request.body.decode('utf-8'))
idinfo = id_token.verify_oauth2_token(json_data['google_token'], requests.Request(), CLIENT_ID)
if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
raise ValueError('Wrong issuer.')
print("idinfo")
print(idinfo)
Now I got the user details here and want to generate an access token to access my API's for every request.
Is there any built in function from oauth2 to generate an access token.
Any suggestion that would help me. Thanks.

Automating Box Authentication - Python

I'm writing an app that interacts directly with my Box account. I need to perform all the operations listed in the Python SDK API. Sure enough, I'm trying to get over the authentication part. Given my client_id and client_secret, I have the following script:
#!/usr/bin/env python
import boxsdk
import requests
def store_tokens_callback(access_token, refresh_token):
# I don't know why this is never being called.
print access_token, refresh_token
oauth = boxsdk.OAuth2(
client_id="<my_client_id>",
client_secret="<client_secret>",
store_tokens=store_tokens_callback,
)
auth_url, csrf_token = oauth.get_authorization_url('http://127.0.0.1')
print auth_url
print csrf_token
r = requests.get(auth_url)
print r.text
client = boxsdk.Client(oauth)
I do get the auth_url:
https://app.box.com/api/oauth2/authorize?state=box_csrf_token_<csrf_tken>&response_type=code&client_id=<client_id>&redirect_uri=http%3A%2F%2F127.0.0.1
However, clicking in that URL all the time won't do it. I need a way to automate this authentication process, so I don't have to click at this button every time:
Sure enough, I could add a little Selenium task to get click on that button and get the url with the code, however I was looking for something easier ... between the lines.
A few questions:
How can I automate the auth process in the Box SDK?
Why isn't stoke_tokens_callback being called?
Check out the enterprise edition documentation, which allows you to interact via API calls only (no button clicking needed).
I had exactly the same requirement. The SDK will handle refreshing the access token when it expires, using the 60 day refresh token. The refresh token itself is also refreshed, meaning it's valid for yet another 60 days. Using the code below, having first "primed" the access and refresh tokens, will be good as long as the API is invoked at least once every 60 days. Follow the Box SDK instructions for obtaining your initial access and refresh tokens. You'll then have to install these Python modules:
pip.exe install keyring
pip.exe install boxsdk
Then use keyring.exe to prime the credential store:
keyring.exe set Box_Auth <AuthKey>
keyring.exe set Box_Ref <RefreshKey>
From here:
"""An example of Box authentication with external store"""
import keyring
from boxsdk import OAuth2
from boxsdk import Client
CLIENT_ID = 'specify your Box client_id here'
CLIENT_SECRET = 'specify your Box client_secret here'
def read_tokens():
"""Reads authorisation tokens from keyring"""
# Use keyring to read the tokens
auth_token = keyring.get_password('Box_Auth', 'mybox#box.com')
refresh_token = keyring.get_password('Box_Refresh', 'mybox#box.com')
return auth_token, refresh_token
def store_tokens(access_token, refresh_token):
"""Callback function when Box SDK refreshes tokens"""
# Use keyring to store the tokens
keyring.set_password('Box_Auth', 'mybox#box.com', access_token)
keyring.set_password('Box_Refresh', 'mybox#box.com', refresh_token)
def main():
"""Authentication against Box Example"""
# Retrieve tokens from secure store
access_token, refresh_token = read_tokens()
# Set up authorisation using the tokens we've retrieved
oauth = OAuth2(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
access_token=access_token,
refresh_token=refresh_token,
store_tokens=store_tokens,
)
# Create the SDK client
client = Client(oauth)
# Get current user details and display
current_user = client.user(user_id='me').get()
print('Box User:', current_user.name)
if __name__ == '__main__':
main()

Authentication and authorization on APIGEE using Python

I am trying to find a way to authenticate and authorize a client to access APIGEE. I can't seem to get it to function. I am using Python Requests-OAuthlib. Here is my code:
from requests_oauthlib import OAuth2Session
client_id = r'my_client_id'
client_secret = r'my_client_secret'
redirect_uri = 'https://api.usergrid.com/org/app'
oauth = OAuth2Session(client_id, redirect_uri=redirect_uri)
authorization_url, state = oauth.authorization_url('https://api.usergrid.com/org/app/token', grant_type='client_credentials')
redirect_response = raw_input(authorization_url)
token = oauth.fetch_token('https://api.usergrid.com/org/app/token', client_secret=client_secret, authorization_response=redirect_response)
url = "https://api.usergrid.com/org/app/my_collection"
r = oauth.get(url)
I get an error: "Please supply either code or authorization_code parameters."
Any ideas on what I am doing wrong? I am using the APIGEE docs found here: http://apigee.com/docs/app-services/content/authenticating-users-and-application-clients
Thank you in advance.
Your client is sending response_type=code in the authorization request. That is why the server is not performing client credential Oauth.
This could be a default behavior of your python client. In that case you might want to use a simple http client to keep things under control.

Categories