Python request to authorize app api made via tyk gateway - python

I'm working on a python script (2.7.x) that tries to connect to a third party api via tyk gateway. The end api expects an auth token in the request header and tyk also requires its own auth token to be present in the request header.
Now the problem that I'm facing is:
When I try to make a request to the third party app via tyk, app is not recognising the auth token passed in the header.
From debugging I was able to figure out that tyk is not passing the authentication header to the app.
I'm using following piece of code to make the request
request.post("https://myurl.com",
data={"data": data_a},
headers={"Authorization": "Basic <TYK_TOKEN>, Bearer <APP_TOKEN> })
Things I have tried:
Tried passing the app token first and tyk token second, then the request won't pass tyk authorization.
Tried passing app token alone in the request, then the request won't pass tyk authorization.
Tried passing app token under 'Application-Authorization' header and tyk token under 'Authorization' header, then the request won't pass app authorization.
Please advise a solution.
Thanks
in advance

Leonid from Tyk here.
So basically your upstream is protected by auth token, and your own API protected by token as well.
If your 3-rd party API have a static api key, you can just embed it to all requests as a global header:
If you have a dynamic 3-rd party key, which varies for different users, you can embed it to Key metadata, for example, "upstream_api_key" field, and add global header with dynamic value: "$tyk_meta.upstream_api_key".
If your user needs to pass this token, and you need forward it to upstream, Tyk and Upstream authentification should happen in different HTTP headers.
Hope it helps!

Related

How to use tokens in frontend for authentication

I am currently developing a React-Django app and using dj-rest-auth package and JWT for authentication on the backend. It works perfectly fine and when a user loggs in, server responses with a HttpOnly cookie which contains access_token.
What I don't understand is how can I use the access_token that in the response-cookie for requests in my web app if I can't read the token value from my frontend since it is HttpOnly?
I tried js-cookie package for storing JWT in cookies and since it is written in JS, I can't make it HttpOnly. So I am storing access_token in a cookie but doesn't it break the point of HttpOnly cookies since they both store the same token value?
you can send the token to your api call on the headers as Authorization Bearer + token

How to send oauth2 access_token in cookies ? (kong oauth2 plugin)

I am using Kong oauth2 plugin to handle authentication for my dash plotly app. Dash plotly does not allow the user to set a custom header for the requests and so it very difficult to add an authentication header to my requests.
These headers work perfectly for normal web pages
"Authorization": "Bearer snakjdnjsbcksnbnddnndnsms" or
"authorization": "snakjdnjsbcksnbnddnndnsms"
However, due to the limitation of Dash Plotly not allowing to set the headers I want to try to send the authorization token in a cookie.
I tried sending a cookie with the "authorization" key and corresponding value via my flask app, however I still get an unauthorized response.
Is this method even possible ? I saw that it works in loopback.token of nodejs using signed cookies. If so how can I achieve this ? Appreciate any help in this regards.
I don’t think, this is even feasible. As per OAuth 2.0 RFC, the access token should be passed as a bearer header.
Typically, it involves
using the HTTP "Authorization" request header field [RFC2617] with an
authentication scheme defined by the specification of the access
token type used, such as [RFC6750].
Link to RFC 6749

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.

How to get the request's Authentication Header in Tornado

I've been looking on how to get the Authorization Header from a Tornado GET/POST Request, but there's none. Anyone can help on this?
The reason is that I want to implement JWT in my Python application.
For example, this tornado API just creates a GET request:
class HeaderHandler(tornado.web.RequestHandler):
def get(self):
headers = tornado.httputil.HTTPHeaders()
response = {
'message': str(headers)
}
self.write(response)
I want to access this API via http://localhost:{port} and I will add a header which is
Authentication: Bearer {token}
But this code doesn't work. It cannot fetch the authorization header passed to the request. Any help is appreciated. Thanks!
In Tornado, accessing the bearer token from JWT can be achieved by:
token = self.request.headers.get('Authorization')
According to the docs, a request object containing headers is available as RequestHandler.request, so try e.g.
self.write(repr(self.request.headers))

Categories

Resources