Oauth 1.0a in Django - python

I'm trying to make authorised calls on the Rdio API in my Django application. I've been looking at the following tutorial so far to get it set up:
http://www.rdio.com/developers/docs/web-service/oauth/ref-oauth1-overview
The code at the bottom of the page works fine for me: I can get the request token, authorise the user using the PIN, and then make a call using the new access token.
However, I'd like to implement the callback so that the user can just log in and return to my site so that I can make authorised requests with their account. I currently have a page with a link to authorise the application, where the function to get the link is like so:
def get_auth_url():
client = oauth.Client(consumer)
response, content = client.request('http://api.rdio.com/oauth/request_token', 'POST', urllib.urlencode({'oauth_callback': 'http://localhost:8080/my_page/'}))
parsed_content = dict(cgi.parse_qsl(content))
request_token = oauth.Token(parsed_content['oauth_token'], parsed_content['oauth_token_secret'])
sURL = '%s?oauth_token=%s' % (parsed_content['login_url'], parsed_content['oauth_token'])
return sURL
This is okay, and when I click this link I go to a page asking to authorise my account for this application. However, I then need to get the access token from the request token that my user has just authorised. The callback from the authorisation page gives me oauth_verifier and oauth_token arguments but constructing the request token requires oauth_token and oauth_token_secret. I had the secret on the first call but can't get it again in this second call, and the tutorial said that I shouldn't store the secret anywhere accessible or transfer it across requests. And since these are two different requests I can't think of where to store the persistent request token. How can I get the oauth_token_secret on this second request so that I can get the access token?

You'll need to store the request token on your server temporarily so you can make the access token request. This line:
The request token secret must be included in the signature but not over the wire.
refers to the fact that the secret is used to generate the signature, but isn't included by itself in the request.
To save yourself some time and effort, I recommend using Django Social Auth. It already supports Rdio.

Related

Capturing access token from an API redirect URL

I am trying to capture my access token that is returned by an API during authentication process. The official method of doing the authentication process from the API is:
from xyz_api import accessToken
app_id = "your_app_id"
app_secret = "your_app_secret"
app_session = accessToken.SessionModel(app_id, app_secret)
response = app_session.auth()
The above will return a json like:
{
"code" : 200,
"data" : {
"authorization_code": "some random code"
},
}
Now, the following code is used to generate a URL:
authorization_code = “your_authorization_code”
app_session.set_token(authorization_code)
url = app_session.generate_token()
Now this is where I start having issue.
At this stage, what is recommended by the API author is:
1. Use the generated URL and copy paste it into a browser.
2. The browser will then do the authentication and return the access token to a redirect
url (I used http://localhost:5000).
3. Copy and paste the access token from redirect URL
What I want:
To be able to finish the authentication and get the access_token from
python code itself.
What I tried:
Using requests.get(url), but it doesn't work.
Is there any way to do this all using python only, without having a need to open a browser?
PS: The API I am trying to use is: https://api-docs.fyers.in/v1#authorization
Further Investigation
On further investigation, I discovered the following:
The API uses oauth
The URL obtained from the following code provided by the API author
url = app_session.generate_token()
is same as when I write the following code:
oauth = OAuth2Session('app_id')
authorization_url, state = oauth.authorization_url(url)
The url returned in both cases is of the form:
https://api.fyers.in/api/v1/genrateToken?authorization_code=some_auth_code&appId=my_app_id
If I copy paste this URL in a browser, it send back the access_token to my redirect_url (http://localhost:5000)
I am trying to get the access token using oauth::fetch_token with the following code, which is failing:
oauth1 = OAuth2Session('app_id', state=state, redirect_uri="http://localhost:5000")
token = oauth1.fetch_token('https://api.fyers.in/api/v1/genrateToken/',
client_secret='app_secret',
code='the_auth_code_returned')
Truly appreciate the help.
you are accessing only with Python...
you dont need to do anything manually in a browser..
This API not sure if what you wnat to.
I Believe you registred an APP , got your app_secret
the step
response = app_session.auth()
answer you with a authorization_code
"data" : {
"authorization_code": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqaGdqZzg3NiQ3ODVidjVANjQ3NTZ2NSZnNyM2OTg3Njc5OHhkIjoiWElHVFVYVjBSSSIsImV4cCI6MTU2MTU5NzM5Ny41NjQxNTV9.Agl-Uus63NforrUEdbG7YUlPcbFXu9hLYm4akGuIBkU"
you may access that authorization token like that
import json
r = json.dumps(reponse)
authorization_token = r['data']['authorization_code']
The authorization token AND you app_id must be passed as querystring to https://api.fyers.in/api/v1/genrateToken?
the REAL user will be then asked to accept login trought your app
and if accepted , the user will be redirected to the URL *I imagined you inform in your app register.
let me know if it make sense

Can't retrieve access token for oauth

I'm trying to implement OAuth for an application that retrieves data from our JIRA server via the REST API. I am able to construct and use an authorization url, and get a message indicating that I have successfully authorized my application when I use it. However, when I then try to request the access-token, I always get response code 401, with content 'oauth_problem=token_rejected'.
I am using Python 3, and have pulled apart the code in the 'oauthdance' function within jirashell to see where the breakdown is happening. I'm not using a callback uri, so I specified 'oob' as the callback and can see the verification string in my browser after I authorize the application.
oauth = OAuth1(consumer_key,
signature_method=SIGNATURE_RSA, rsa_key=key_cert_data, resource_owner_key=request_token, resource_owner_secret=request_token_secret, verifier=<string copied from browser>
)
r = requests.post(
server + '/plugins/servlet/oauth/access-token', verify=verify, auth=oauth)
I would expect this code to retrieve the access token, but instead it's returning the 401 response. The request_token and request_token_secret appear to be valid and were retrieved via the request-token servlet.
I found the answer here: https://community.developer.atlassian.com/t/java-oauth-example-does-not-work/3779/2
The consumer key used with OAuth is case-sensitive. I changed it to exactly match the value entered by our admin in JIRA and got an access token.

How to get oauth2-token for Google Analytics Reporting API (REST method) in Python

I want to route my Google Analytics Reporting API request (code will be in AWS Lambda) through a gateway which accepts a REST endpoint only. Since I cant use the Client package method in my interaction with the gateway, I need to query the API as a REST-ful endpoint.
The official document says this (Link) :
Authorization: Bearer {oauth2-token}
GET https://www.googleapis.com/analytics/v3/data/ga
?ids=ga:12345
&start-date=2008-10-01
&end-date=2008-10-31
&metrics=ga:sessions,ga:bounces
I do not know to create the oauth2-token in Python. I have created a service account and have the secrets_json which includes the client id and secret key.
Then client package method as given in this link works. But I need the Rest method only!
Using these, how can I create the oauth2-token ?
You can use Oauth2 for this I have done it in the past but you will need to monitor it. You will need to authorize this code once and save the refresh token. Refresh tokens are long lived they normally dont expire but your code should be able to contact you if it does so that you can authorize it again. If you save the refresh token you can use the last step at any time to request a new access token.
Oauth2 is basicly built up into three calls. I can give you the HTTP calls i will let you work out the Python Google 3 Legged OAuth2 Flow
Authencation and authorization
The first thing you need is the permission of the user. To get that you build a link on the authorization server. This is a HTTP get request you can place it in a normal browser window to test it.
GET https://accounts.google.com/o/oauth2/auth?client_id={clientid}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code
Note on redirect uri. If you are running this on a server or something then use urn:ietf:wg:oauth:2.0:oob it basicly tells the server to return the code back where it came from other wise if you are hosing on a website you can supply a url to the page that will be handling the response.
If the user accepts the above then you will have an authorization code.
Exchange code
What you need to do next is exchange the authorization code returned by the above response and request an access token and a refresh token. THis is a http post call
POST https://accounts.google.com/o/oauth2/token
code=4/X9lG6uWd8-MMJPElWggHZRzyFKtp.QubAT_P-GEwePvB8fYmgkJzntDnaiAI&client_id={ClientId}&client_secret={ClientSecret}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code
The body parameter should be as i have shown separated by & and the content type of the request is application/x-www-form-urlencoded
Responce
{
"access_token" : "ya29.1.AADtN_VSBMC2Ga2lhxsTKjVQ_ROco8VbD6h01aj4PcKHLm6qvHbNtn-_BIzXMw",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "1/J-3zPA8XR1o_cXebV9sDKn_f5MTqaFhKFxH-3PUPiJ4"
}
The access token can be used in all of your requests to the api by adding either an authorization header bearer token with the access token or by sending access_token= as your parameter in your requests.
Refresh access token
Refresh tokens are long lived they should not expire they can so you code should be able to handle that but normally they are good forever. Access tokens are only valid for one hour and you will need to request a new access token.
POST https://accounts.google.com/o/oauth2/token
client_id={ClientId}&client_secret={ClientSecret}&refresh_token=1/ffYmfI0sjR54Ft9oupubLzrJhD1hZS5tWQcyAvNECCA&grant_type=refresh_token
response
{
"access_token" : "ya29.1.AADtN_XK16As2ZHlScqOxGtntIlevNcasMSPwGiE3pe5ANZfrmJTcsI3ZtAjv4sDrPDRnQ",
"token_type" : "Bearer",
"expires_in" : 3600
}

Use JWT with TurboGears2

I'm currently stopped in my work because of some authentication work on a project.
I set up a REST API, which needs to have a JWT authentication system.
Some work was already done and I overrode it. So the library used was Python's TurboGears2, and I used PyJWT to manage tokens.
My WS and the token's creation works well. The post method with auth info JSON request's body can create a token, that's sent in the response.
But after that, when I do a 'GET' request on the restricted resource, I can't retrieve the token.
What I do: send a GET request to the restricted resource, with "Authorization: Bearer <TOKEN>" in request headers.
But when I do a 'request.authorization' in my web service function, I always get 'None'.
Do I need to set up a full auth system using TurboGears to access this header?
thanks for help
Where are you trying to access the request.authorization from?
I tried with a newly quickstarted application and modified the index to print the authorization header:
#expose('testauth.templates.index')
def index(self):
"""Handle the front-page."""
print(request.authorization)
return dict(page='index')
And I sent the authorization header from Postman.
It worked fine and printed my test header
Authorization(authtype='Bearer', params='HELLO')
I also tried to disable any auth_backend so that authentication is disabled and it still works as expected.

OAuth: Receive callback with parameters as POST data

I'm new to OAuth, I'm using the oauth2 library on Python to get my work done.
Currently when I receive a callback from the server, the parameters come in the URL as:
http://mydomain/?oauth_verifier=(SOME_DATA)&oauth_token=(SOME_DATA)&oauth_callback_confirmed=true
I'm wondering if it's possible to instruct the server to somehow POST those parameters (oauth_verifier, oauth_token, oauth_callback_confirmed) to me as a callback and not show them in the URL (as a GET request)?
Thank you!
No, it is not possible to encode the callback parameters as a POST request. The OAuth 1.0 Spec says that the provider issues an HTTP Redirect to the callback URL:
If the Consumer provided a callback URL in oauth_callback (as
described in Consumer Directs the User to the Service Provider), the
Service Provider constructs an HTTP GET request URL, and redirects the
User’s web browser to that URL with the following parameters:
Since an HTTP Redirect can only be a GET, not a POST, your callback can only contain the parameters in the URL.

Categories

Resources