I'm using both Appcelerator Titanium and Python's Django to create a mobile app. As you might have guessed, Django is being used for the back-end. At the moment I'm trying to create a login form which requires a CSRF token to accept the data correctly. I'm trying to retrieve the CSRF token from Django, but I've tried and failed, and Google doesn't have any answers for me.
The problem is normally you'd get an HTML page with a CSRF token included in the form and just send it. What I'm trying to do now is send a POST without knowing the CSRF. In appcelerator, I've tried running
HTTPSession.open(GET, *url*)
token = HTTPSession.getRecievedHeaders("X-CSRF-TOKEN")
HTTPSession.open(POST, *url)
HTTPSession.getRecievedHeaders("X-CSRF-TOKEN", token)
HTTPSession.send(data)
But this doesn't work because of how Titanium works. So how can I get the token? Do I need to create a specific url just to create a session and display a CSRF token? I'm just worried that once I've recieved the token, I'll need to reconnect to the server and the token will have changed.
During my Googling, I found that Drupal has a function for this at the url: services/session/token
Is there an equivillant for this in Django? Or do I need to create my own page showing just a CSRF token?
If you are using Titanium for app creation you can use SetRequestHeader for setting the token with the request.
Hope it helps.
I needed to create my own function in Django to achieve this, but I finally got it working!
function getCSRF() {
var csrfHTTP = Ti.Network.createHTTPClient({
onload : function() {
Ti.App.Properties.setString("csrf", this.responseText);
}
});
csrfHTTP.open("GET", "http://website.com/api/csrftoken/");
csrfHTTP.send();
}
Then retrieve it via
Ti.App.Properties.getString("csrf")
and use it:
loginHTTP.setRequestHeader("X-CSRFToken", Ti.App.Properties.getString("csrf"));
Connecting to the website once creates a session in Django also creating a csrf token for that specific IP to use so you can retrieve it multiple times if needed
Related
I'm working on a multi-league fantasy football assistant, where a the user has there choice between a few platforms they can login to and import selected leagues from a list of all their avb leagues from that platform. Reactjs + Node.js frontend & Python + Django Rest backend (MySQL db)--working on just Sleeper functionality at the moment though.
I have tried a number of different ways, including trying to make a POST request to https://api.sleeper.app/v1/auth/login and I am having no luck! I keep getting a 404 status. I even tried a GET request to see what the URL returned and still nothing. If there is no exact URL, how should I go about getting user's logged in to Sleeper and get their initial info (mainly username) in order to go about my other requests?
Tried making POST requests in Postman with the https://api.sleeper.app/v1/auth/login URL using the below as my 'body' and was getting 404 status codes back.
{
"username": "my_usernam_here",
"password": "my_password_here"
}
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
}
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.
I have access to an API that I'm trying to start leveraging to automate some tasks and I jumped right into it but was stymied by JWT, which I have never used. I'm also coming off a couple years not using python, so I'm a little rusty. Please bear with me.
Here is a direct quote from the API documentation:
The authentication mode for an organization is with a JSON Web Token. Users
must pass a JSON Web Token (JWT) in the header of each API request made.
To obtain the JWT, send the user’s API key (UUID) and password in a JSON Web
Token GET Request. The authorization method of “Bearer” and a
space is then prefixed to the encoded token string returned. The token will
be tied to the user account that generated the JWT.
I've tried with requests but I'm get 405 errors, I've also installed and imported pyjwt but it's confusing to me. This is essentially what I'm trying to send via python:
POST https://<our endpoint>/v1/token/get HTTP/1.1
Content-Type: application/json
{
"username": "<myUsername>",
"password": "<myPassword>"
I've verified that the target API is working, as there is a small set of functionality that works without JWT and was easily accessed via requests
Advice is welcome, as are any tutorials. I've tried to read several JWT tutorials but I'm having a hard time translating it to python.
Thanks!
Question: To obtain the JWT, send the user’s API key (UUID) and password in a JSON Web Token GET Request
Solution using python_jwt.
Assumptions:
Encoding Method = HS256
claims Fieldname 'consumerId'
claims Fieldname 'httpMethod'
Your JWT in the url looks like:
'http://httpbin.org/get?eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJIUzI1NiJ9... (omitted for brevity)
response.json() contains the requested JWT you have to use afterwards.
Note: Your have to use https://<base url>/v1/token/get
import python_jwt as jwt
# Create claims dictionary for generation of JwToken
claims = {
'consumerId': 'My App ID',
'httpMethod': 'GET'
}
import datetime
# create JWToken
jwtoken = jwt.generate_jwt(claims, 'My secret', 'HS256', datetime.timedelta(minutes=5))
response = requests.get('http://httpbin.org/get', jwtoken)
print(response.json())
Tested with Python:3.4.2 - requests:2.11.1
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.