My locally hosted bot that's integrated with Google Hangouts API uses python's Tornado module to accept user input from Google and responds with an appropriate reply. This is the request handler on the bot server:
class incomingRequestHandler(tornado.web.RequestHandler):
def post(self):
recievedData = json.loads(self.request.body.decode('utf-8'))
responseData = generateResponse(recievedData)
self.write({ 'text' : responseData })
This works great. Now I want to authenticate the incoming requests to make sure they're only coming from Google Hangouts.
The request from Google does have an Authorization bearer token in it's header and I'm sure that's what needs to be used for verification. As such, based on this article I took the recommended measures like using id_token.verify_oauth2_token() or querying https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123 but neither solution seems to work.
Could someone point me in the right direction for this? Am I using the correct token even or is this the wrong method for verifying incoming requests?
This issue originated from me having no idea what a JWT was nor knowing that what I'd encountered was a JWT. Another symptom of trying to handle things yourself, I guess.
Anyway, the solution is simply to get the Google certificates from this link, use openssl to generate corresponding public keys and feed the key specified (by kid value) in the authentication token to the jwt.decode() method of python's jwt module.
Here's a snippet of the solution:
selectedKey = certs.get(jwtHeader.get('kid')) //certs is a dict containing the public keys from Google
checksum = jwt.decode(token, selectedKey, algorithms=["<value-of-alg>"], audience="<value-of-aud>", issuer="<value-of-iss>") //token is simply the authentication token as a string
Note the following bash command to be sued to convert Google's x509 certificates into pem format public keys:
openssl x509 -pubkey -noout -in key.pem
I don't think python has a very modular solution for the above yet. Do let me know if there is.
Related
I'm using the site https://www.hurl.it/#top to make a POST HTTP request to the Poloniex Exchange API.
Note that I have generated my Sign by going to https://www.freeformatter.com/hmac-generator.html#ad-output putting my SECRET and API_KEY into the given fields, and choosing the SHA512 algorithm.
I have filled out the fields at https://www.hurl.it/#top with the following (All fields are verbatim other than API_KEY and SECRET for obvious reasons):
Destination
POST: https://poloniex.com/tradingApi
Headers
Key: API_KEY
Sign: SECRET
Parameters
nonce: 0001
command: returnBalances
I am then given the error:
{"error":"Invalid API key\/secret pair."}
What am I doing wrong? Am I not following the API requirements for an HTTP request verbatim? Also I am not looking for any libraries/programming languages to use. I am looking to make this work using this website or something similar, because once I do, I will have what I'm looking for.
Note that I have generated my Sign by going to https://www.freeformatter.com/hmac-generator.html#ad-output putting my SECRET and API_KEY into the given fields, and choosing the SHA512 algorithm.
Api & secret are very sensitive data, so take care to:
- Never share your api key and secret on a tier website. (it could be store and be reuse)
- Never send a request containing your api key and secret in clear. (it could be intercepted by a MIM attack and/or your ISP and/or DPI)
Finally :
You may compute yourself (locally) the signature using a PHP wrapper recommended on the Poloniex Api documentation page
I am trying to connect to Google Cloud from an embedded device so I have no access to OAuth authentication. The documents show that I can use simple API key for connecting. I have created a simple API key but I am having problems using it.
I can test the API functions successfully on https://developers.google.com/apis-explorer/?hl=en_US#p/pubsub/v1/ but on this developer's site I don't enter my API key (maybe one is generated automatically in the background).
When I try the same command using curl I get a 401 error:
"Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "status": "UNAUTHENTICATED"
But I am copying the GET or POST command directly from the online API tester and adding my key at the end:
curl -X POST -d '{"policy":{"bindings":[{"role":"roles/editor","members":["serviceAccount:charge...."]}]}}' https://pubsub.googleapis.com/v1/projects/pl..../subscriptions/arriveHomeSub:setIamPolicy?key=AIz....
What am I missing?
With the limited information you have provided, it is tough to identify the root cause but these are some of the possible ones:
You have not used quotes for the URL argument to curl. This could lead to some characters which are part of the URL to be interpreted by your shell in a different manner. Characters like & are usual culprits although they don't seem to be part of the URL you pasted.
curl -X POST -d '{"policy":{"bindings":[{"role":"roles/editor","members":["serviceAccount:charge...."]}]}}' 'https://pubsub.googleapis.com/v1/projects/pl..../subscriptions/arriveHomeSub:setIamPolicy?key=AIz'
You have not described how you're generating your API key and hence I feel that could be one of the possible issues.
You can go over the steps for using Google OAuth 2.0 from Google, it covers a lot about client secrets, access tokens and refresh tokens.
As long as you have your client ID and secret, you can call Google OAuth APIs to generate an access token.
You pass in the current access token as the key argument to your REST API.
Access tokens have very limited lifetime and might need refreshing periodically. If your application needs to periodically refresh access tokens, consider storing the refresh token in your application in a secure manner.
I have a mobile app which will call a REST API written using Laravel(5.2) framework.
This article on Laravel API authentication mentions how to authenticate users making calls to such an API. The caller should send the correct api_token to the server in the request.
My question is what would be a good way to get the api token to the mobile app? I'm currently thinking of creating a rest api which will authenticate the user based on username and password sent in the request and send the api_token in the response if the user sends a valid username/password pair. Is this method correct/secure? What things should I consider additionally if I do use this method?
You must use one of this methods to have a secure API
JWT TOKEN https://github.com/tymondesigns/jwt-auth
OAUTH2 https://github.com/lucadegasperi/oauth2-server-laravel
With this methods you only send once username and password and you obtain a token that is valid for a time you can decide. But as bigger is the time, more insecure.
To solve this, there are a renew token methods. With a valid token, you can obtain another valid and refresh the old. In this way, the username and password are more protected because they are not sent in every request.
Is not a good idea have the same token for each user all the time, as you saw in the example you provide. It´s very insecure. If someone get this token, he always will can send request in your name. The tokens must have a lifetime.
to answer your question how to send API token to mobile app i will recommend you that your mobile apps get a valid token and after refresh it.
Something as this works great to get a token in your app:
if ( thereAreTokenStored() )
{
if (! theTokenStoredIsValid() )
{
$authentication = refreshToken();
}
}
else
{
$authentication = authenticate();
}
To know all this issues I recommend you this book: https://apisyouwonthate.com/ . I learnt a lot of the 'API WORLD' with this book. It will help you to know all you need to create an API in a professional way and will provide the necessary tools and packages to achieve it and save a lot of work. And you will love your API!!
Yes this approach is safe. Additionally you also need to secure your connection to server by using HTTPS with a SSL certificate.
After reading James Wards artice on Securing Single Page Apps and REST Services, I'd very much like to implement this in Dart. However I have found so few examples in Dart on the topic of authentication. I'm particularly interested implementing steps 6 - 9 from the article:
The server validates the login information and creates an
authentication token for the user
The server sets the authentication
token in a cookie and returns it to the JavaScript application
The JavaScript application makes a request for some protected data,
sending the authentication token in a custom header
The server validates the token and then returns the data
Can someone provide a simple client/server example of this in Dart. Thanks in advance.
I would suggest the easiest thing to do is to use the Google OAuth2 pub package with Dart on the server to generate a token as described in this tutorial.
If you want to use cookies to store the token as James suggests, you can do so like this:
document.cookie = "token=TOKEN;max-age=${60*60*24*7*4}";
You read the cookie like this:
var token = document.cookie.replace(/(?:(?:^|.*;\s*)token\s*\=\s*([^;]*).*$)|^.*$/, "$1");
And send it back in a custom header like this:
HttpRequest req = new HttpRequest();
req.open("Get", "www.server.com");
req.setRequestHeader("custom-token-header", token);
Then you can validate the token as described in the tutorial.
I've searched all over (including here on Stackoverflow) for how to use the Magento REST API. I need help on getting an Unauthorized Request Token (the first step)
On the Magento setup I'm using the REST API is working for GET Products for Guests so I know that is not [the problem][1]
I have setup an OAuth Consumer for the above URL and have both the consumer key and secret. I can't figure out what URL to use for the Callback URL.
First, I'm stuck and don't know what I should use as the Callback URL when setting up the consumer. It is an optional field in Magento
I'm testing with the Firefox REST Client as per http://www.magentocommerce.com/api/rest/testing_rest_resources.html
Next with the Firefox REST client I can't get started by getting an Unauthorized Request Token. According the above URL I should have the oauth_callback URI in the header.
The following request parameters should be present in the Authorization header:
oauth_callback - an URI to which the Service Provider will redirect the resource owner (user) after the authorization is complete.
oauth_consumer_key - the Consumer Key value, retrieved after the registration of the application.
oauth_nonce - a random value, uniquely generated by the application.
oauth_signature_method - name of the signature method used to sign the request. Can have one of the following values: HMAC-SHA1, RSA-SHA1, and PLAINTEXT.
oauth_signature - a generated value (signature).
oauth_timestamp - a positive integer, expressed in the number of seconds since January 1, 1970 00:00:00 GMT.
oauth_version - OAuth version.
What is the oauth_callback URI when using the above URL?
When I try a POST to Endpoint: /oauth/initiate
I get:
oauth_problem=parameter_absent&oauth_parameters_absent=oauth_callback
I'm lost and don't know what else to try. I'm a novice programmer and new to the Magento REST API...so keep that mind. It may be that I'm just missing the obvious.
Anyone who is interested in helping me figure this out here are the Consumer key and the secret.
key: d2f4a7cc63715f98d12db2c6db63cfba
secrect: 8347474102cbf2d40b06f9d76f281e73
The URL is: http://temp.pramier.com
This is from a test install so I'm not worried about giving out the key and secrect
Pass the oauth_callback like http://temp.pramier.com/admin.
You is in this step:
Getting an Unauthorized Request Token
The first step to authenticate the user is to retrieve a Request Token from Magento. This is a temporary token that will be exchanged for the Access Token.
Endpoint: /oauth/initiate
Description: The first step of authentication. Allows you to obtain the Request Token used for the rest of the authentication process.
Method: POST
Returns: Request Token
Sample Response: oauth_token=4cqw0r7vo0s5goyyqnjb72sqj3vxwr0h&oauth_token_secret=rig3x3j5a9z5j6d4ubjwyf9f1l21itrr&oauth_callback_confirmed=true
You should continue to get the token.
This is the best (and official) tutorial:
http://devdocs.magento.com/guides/m1x/api/rest/authentication/oauth_authentication.html#OAuthAuthentication-UsingOAuth
I am not sure what programming language you are using, but the API lists the code for authenticating and retrieving products in php on the bottom.
I just started working on this in ruby using the code here.
#consumer=OAuth::Consumer.new auth["consumer_key"],
auth["consumer_secret"],
{:site=>"your-site-here"}
#request_token = #consumer.get_request_token
Let me know if I misunderstood your question or wasn't clear in my explanation.
Please follow those instructions here:
http://inchoo.net/magento/configure-magento-rest-and-oauth-settings/
After that, follow these steps:
http://www.aschroder.com/2012/04/introduction-to-the-magento-rest-apis-with-oauth-in-version-1-7/
At the beginning of the article, the writer asks to use a Ruby program called oAuth. If you are using Linux, put these commands into the command line to install Ruby and oAuth:
sudo apt-get install ruby
and
sudo gem install oauth
Beware, if you put exactly this:
--authorize-url http://www.yourstore.com/magento/oauth/authorize \
You'll get a permissions error when you'll want to login. You should replace this by:
--authorize-url http://www.yourstore.com/magento/admin/oauth_authorize \
Everything should go smoothly.