I'm using OAuth with Federated Login (Hybrid Protocol) to allow my users to login once using openID (which works great), and authenticate with the Google Data API at the same time.
The Zend_GData library was giving me a headache, so on the suggestion of someone here on SO I switched to LightOpenID.
The openID part works great, and thanks to this tip I'm able to add the OAuth extension and receive a response like this:
http://www.example.com/checkauth
?openid.ns=http://specs.openid.net/auth/2.0
&openid.mode=id_res
&openid.op_endpoint=https://www.google.com/accounts/o8/ud
&openid.response_nonce=2009-01-17T00:11:20ZlJAgbeXUfSSSEA
&openid.return_to=http://www.example.com/checkauth
&openid.assoc_handle=AOQobUeYs1o3pBTDPsLFdA9AcGKlH
&openid.signed=op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle,ns.ext2,ext2.consumer,ext2.scope,ext2.request_token
&openid.sig=oPvRr++f6%2ul/2ah2nOTg=
&openid.identity=https://www.google.com/accounts/o8/id/id=AItOawl27F2M92ry4jTdjiVx06tuFNA
&openid.claimed_id=https://www.google.com/accounts/o8/id/id=AItOawl27F2M92ry4jTdjiVx06tuFNA
&openid.ns.oauth=http://specs.openid.net/extensions/oauth/1.0
&openid.oauth.scope=http://docs.google.com/feeds/+http://spreadsheets.google.com/feeds/+http://sandbox.gmodules.com/api/
&openid.oauth.request_token=1/fVr0jVubFA83GjYUA
According to the documentation, openid.oauth.request_token is an authorized request token, so it seems I don't need to do the OAuthAuthorizeToken request. All is good so far, but now I need to exchange this request token for an access token and token secret.
Since I have no idea how to generate the OAuth nonce and signatures, I employ the OAuthSimple library for php. Problem is, the code required looks like this:
// Build the request-URL...
$result = $oauth->sign(array(
'path' => 'https://www.google.com/accounts/OAuthGetAccessToken',
'parameters' => array(
'oauth_verifier' => $_GET['oauth_verifier'],
'oauth_token' => $_GET['oauth_token']),
'signatures' => $signatures));
It needs an oauth_verifier value, which you would receive along with the request token with a normal OAuth request. I'm not sure if it's the OAuthSimple library that errors out when trying to omit that or if it's a Google requirement, but it doesn't work.
SO, can someone spot something I'm doing wrong here?
There's nothing wrong. Actually, when you do an Hybrid process, the verifier isn't send, simply because you don't need it.
So in your code, just set verifier to NULL, and it should work just fine, as long as there's no problems somewhere else.
Related
I would like to send email messages with our corporate emails provided by Gmail. In order to do that, I would like to use Gmail API with rest commands (basically launched with a php procedural code, for legacy purpose).
I have that code :
I go to this url :
// https://accounts.google.com/o/oauth2/auth?client_id=my_client_id&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/gmail.send&response_type=code
// and obtain a token like that : 4/1AX4XfWgmW0ZdxXpJn8YzkVeDs3oXZUHyJcR7abE2TuqQrcmo4c1W02ALD4I
/*
echo GoogleAuthCurl("GET", '', array(
'client_id' => $GOOGLE_CLIENT_ID,
'redirect_uri'=>'urn:ietf:wg:oauth:2.0:oob',
'scope' => 'https://www.googleapis.com/auth/gmail.send',
'response_type' => 'code'
), array());
then I can use requests in curl for getting my access token :
curl \
--request POST \
--data "code=[Authentcation code from authorization link]&client_id=[Application Client Id]&client_secret=[Application Client Secret]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code" \
https://accounts.google.com/o/oauth2/token */
$tokenJson = json_decode( GoogleTokenCurl("POST", '', array(), array(
'code' => '4/1AX4XfWiEWngRngF7qryjtkcOG1otVtisYpjHnej1E54Pujcrchef8REvdt0',
'client_id' => $GOOGLE_CLIENT_ID,
'client_secret' => $GOOGLE_CLIENT_SECRET,
'redirect_uri'=>'urn:ietf:wg:oauth:2.0:oob',
'grant_type' => 'authorization_code'
)
));
print_r($tokenJson);
This far, I've got food for my authorization header. My issue is in the first step (with the consent asked to user). I wish i can do this step without putting my url in the browser, validate two screens to grant access before getting the authorization code.
I'm also interested in advices to create gmail messages with rest requests driven by curl. I found postman collection about all actions gmail api can do, but one or two call examples wouldn't do harm ;)
thanks !
In the current state, by the method you are using, &response_type=code, you need two calls to the OAuth client to get the access token. You can find an example of how to handle it just using HTTP/REST requests here.
In any case, you could use Google API Client Library for PHP. Allows you to handle the OAuth authentication flow, only needing one interaction to get the token.
You can find a full example on how this works here, notice that this example uses the Drive API, if you want to use it within the Gmail API, you can check Gmail API PHP library.
Documentation:
PHP Gmail API
OAuth 2.0 to Access Google APIs
I‘m trying to call the WooCommerce/Wordpress API, but the online shop that I‘m trying to reach has HTTP Basic Autj turned on. That means, I need to authenticate once to overcome the HTTP authentication and then I need to authenticate a second time using the api key in order to use the api. Is there a possibility to make an api call whilst overcoming two levels of authentication?
The problem is that if I try to authenticate, I use the following code:
$headers = array('Accept' => 'application/json');
$options = array('auth' => array($username, $password));
$request = Requests::get("$url/$api/$model", $headers, $options);
then I get a 401 (unathorised) response from the api, because I didn't send the api token in my request. But if I use the api token and secret instead of the username and password, I don't even get near the api because I don't overcome the http basic authentication.
Thanks for yout help!
From the looks of it, you're having an issue calling your website due to HTTP Basic Auth.
When it comes to authentication on https://your.site, you can connect to https://your.site and enter foo as the user and bar as the password, OR you can connect to https://foo:bar#your.site.
Hope I helped!
I can't comment on your question for clarification as I don't have the rep. So here goes with an answer!
I think the answer is that you will not overcome two levels of authentication in one call. You will likely contact the server first for an access token using your username and password.
Basic authorization usually means that in the initial http request you set the headers to include 'Authorization': 'Basic _______________________' and then in place of the underscores put a long alphanumeric string that is generated by base64-encoding your username and password (that you would log into WooCommerce with I presume) like so: username:password, and including that colon in between.
If I actually base64 encode username:password it comes out to dXNlcm5hbWU6cGFzc3dvcmQK
so when setting your initial http request headers, include:
'Authorization' : 'Basic dXNlcm5hbWU6cGFzc3dvcmQK'
Except base64 encode you're own username and password (separated by the colon!).
Assuming this works, the api may return an access token to you in a few ways. But if you follow the docs you should be able to figure it out from this point.
Again, really not clear on what you're question is exactly but can't comment so I took a shot. Good luck
I'm new to bigcommerce and jwt tokens. I'm trying to get the customer login api to work on a trail store. But have not been able to successfully login a customer automatically.
I got it to work once or twice, but now it doesn't work anymore, and an unable to figure out the odd behavior since nothing changed with the code. I've tried googling if anyone else has had issues with the customer login api but have found nothing.
I've gone thru the tutorial on https://developer.bigcommerce.com/api/v2/#customer-login-api and copied the example provided.
Is there something I'm missing with the code below?
I've gone to developer.bigcommerce.com and created a draft app.
I got the Client ID and Client Secret from the draft app.
I've gone into my trial store and successfully installed the draft app.
I've tested this page on SSL as well.
Could it be because it's a trail store and it will only work if it's a real store?
Thanks.
Here is the php code below:
include "vendor/autoload.php";
use Bigcommerce\Api\Client as Bigcommerce;
use Firebase\JWT\JWT;
function getCustomerLoginToken($id, $redirectUrl = '', $requestIp = '') {
/*
if (empty(self::$client_secret)) {
throw new Exception('Cannot sign customer login tokens without a client secret');
}
*/
$payload = array(
'iss' => '#MyApp1's Client ID#',
'iat' => time(),
'jti' => bin2hex(random_bytes(32)),
'operation' => 'customer_login',
'store_hash' => '#Store Hash#',
'customer_id' => $id
);
if (!empty($redirectUrl)) {
$payload['redirect_to'] = $redirectUrl;
}
if (!empty($requestIp)) {
$payload['request_ip'] = $requestIp;
}
return JWT::encode($payload, "#MyApp1's Client Secret#", "HS256");
}
$jwt = getCustomerLoginToken(1);
header("Location: " . 'https://store-#Store Hash#.mybigcommerce.com/login/token/' . $jwt);
exit();
There are a couple of constraints that can cause errors:
The app must be installed on the store (seems like you're all good here - you can also test with an API token created locally in the store - https://support.bigcommerce.com/articles/Public/Store-API-Accounts/)
The app must have the Login OAuth scope
The JWT URL must be visited within about 30 seconds, or it won't work.
The computer/server that's generating the JWT needs to have a clock that's synchronized, otherwise your IAT value will appear to have been created more than 30 seconds ago or even in the future which will fail.
The URL can only be visited exactly once - if anything runs a GET request against it other than the intended end user's browser, it won't work. For example, if you send the URL in a Slack message, slack will try to preview the link by visiting it and therefore invalidate it.
It's good to double-check that your JWT is valid at https://jwt.io/
BigCommerce support has access to logs which can shed more light on the situation if you've ruled out the above.
Hope this helps!
do not need app client_id and Secret code , you need to api's client_id and secret code
I'm trying to use the Google API v3 to access one google calendar and according to the documentation here : http://code.google.com/apis/calendar/v3/using.html#intro and here : https://code.google.com/apis/console/, the solution I need is the "Simple API Access" & "Key for server apps (with IP locking)".
Now, when I create a page with this code :
session_start();
require_once 'fnc/google-api-php-client/src/apiClient.php';
require_once 'fnc/google-api-php-client/src/contrib/apiCalendarService.php';
$apiClient = new apiClient();
$apiClient->setUseObjects(true);
$service = new apiCalendarService($apiClient);
if (isset($_SESSION['oauth_access_token'])) {$apiClient->setAccessToken($_SESSION['oauth_access_token']);
} else {
$token = $apiClient->authenticate();
$_SESSION['oauth_access_token'] = $token;
}
and in my "config.php" file I add ONLY my developper key (in place of the "X") :
global $apiConfig;
$apiConfig = array(
// True if objects should be returned by the service classes.
// False if associative arrays should be returned (default behavior).
'use_objects' => false,
// The application_name is included in the User-Agent HTTP header.
'application_name' => '',
// OAuth2 Settings, you can get these keys at https://code.google.com/apis/console
'oauth2_client_id' => '',
'oauth2_client_secret' => '',
'oauth2_redirect_uri' => '',
// The developer key, you get this at https://code.google.com/apis/console
'developer_key' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
// OAuth1 Settings.
// If you're using the apiOAuth auth class, it will use these values for the oauth consumer key and secret.
// See http://code.google.com/apis/accounts/docs/RegistrationForWebAppsAuto.html for info on how to obtain those
'oauth_consumer_key' => 'anonymous',
'oauth_consumer_secret' => 'anonymous',
But then I get errors and it tells me it's trying to authenticate using the "OAuth 2.0" system which I don't want to use. I only want to access one calendar with an API key.
And amazingly, when I search in google "Simple API Access key" I find nothing, nothing on their docs, no examples, no tutorials, nothing. Am I the only one using this thing?
So can someone tell me what I'm doing wrong?
(i know this is an old question but i would've been glad if someone
gave a real answer here so i'm doing it now)
I came on the same problem, Simple API access is not well documented (or maybe just not where i searched), but using the Google API Explorer i found a way to get what i need, which is in fact pretty straightforward. You don't need specific lib or anything : it's actually really simple.
In my case i simply needed to search a keyword on G+, so i just had to do a GET request:
https://www.googleapis.com/plus/v1/activities?query={KEYWORD}&key={YOUR_API_KEY}
Now, for a calendar access (see here), let's pretend we want to fetch access control rules list. We need to refer to calendar.acl.list which give us the URI :
https://www.googleapis.com/calendar/v3/calendars/{CALENDAR_ID}/acl?key={YOUR_API_KEY}
Fill in the blanks, and that's pretty much all you need to do. Get a server key (API Access submenu), store it somewhere in your project and call it within URIs you're requesting.
You cannot access your calendar information using API Key. API keys (or simple API acess key) are not authorized tokens and can only be used for some API calls such as a Google search query etc; API keys will not let you access any user specific data, which I am assuming is your objective through this calendar application.
Also, from what I see in your code, you are creating a client object which is going to use OAuth 2.0 authentication and hence you are getting authentication error messages.
There is no such a thing called Simple API Access key.
Normally OAuth 2.0 is used for authorization. But since you have your reason not to use it.
If you want to use OAuth1.0 for authorization. You need an API key in Simple API Access section on the API Access page.
If you want to use username & password login instead of OAuth, you can refer to ClientLogin, but this is not recommanded.
I got to this thread when trying to do the same today. Although this is way late, but the answer is YES, there is actually simple API key for those apis that does not need user authorizations, and the official client library support this.
The api library do this by Options, which is key, value pair.
Take the example of get information of a given youtube video, you would use this api: https://godoc.org/google.golang.org/api/youtube/v3#VideosListCall.Do
To use api key, simply make a type that implements the CallOption interface, and let it return the api key:
type APIKey struct {
}
func (k *APIKey) Get() (string, string) {
return "key", "YOU API KEY HERE"
}
Then when calling the API, supply the APIKey to it:
youtube, err := youtube.New(&http.Client{})
call := youtube.Videos.List("snippet,contentDetails,statistics").Id(id)
rsp, err := call.Do(opt)
This way, you can construct the youtube client with the vallina http client, rather than oauth client, and enjoy the simple api key.
The first answer said you can use http GET directly, but then you will need to handle the errors and parse the result yourself.
See below link which is helpfull to you. The Google API Client Library enables you to work with Google APIs such as Analytics, Adsense, Google+, Calendar, Moderator, Tasks, or Latitude on your server, in the language of your choice.
http://code.google.com/p/google-api-php-client/
Thanks,
Chintu
I am trying to write a small webapp that pulls data from Yammer. I have to go through Yammer's OAuth bridge to access their data. I tried using the Oauth php library and do the 3 way handshake. But at the last step, I get an error stating I have an invalid OAuth Signature.
Here are the series of steps:
The first part involves getting the request Token URL and these are the query parameters that I pass.
[oauth_version] => 1.0
[oauth_nonce] => 4e495b6a5864f5a0a51fecbca9bf3c4b
[oauth_timestamp] => 1256105827
[oauth_consumer_key] => my_consumer_key
[oauth_signature_method] => HMAC-SHA1
[oauth_signature] => FML2eacPNH6HIGxJXnhwQUHPeOY=
Once this step is complete, I get the request Token as follows:
[oauth_token] => 6aMcbRK5wMqHgZQsdfsd
[oauth_token_secret] => ro8AJxZ67sUDoiOTk8sl4V3js0uyof1uPJVB14asdfs
[oauth_callback_confirmed] => true
I then try to authorize the given token and token secret by passing the parameters to the authorize url.It takes me to Yammer's authentication page where I have allow my app to talk to Yammer.
Yammer then gives me a 4 digit code that I have to put back into my application which then tries to acquire the permanent access token. I pass the following information to the access token URL:
[oauth_version] => 1.0
[oauth_nonce] => 52b22495ecd9eba277c1ce6b97b00fdc
[oauth_timestamp] => 1256106815
[oauth_consumer_key] => myconsumerkey
[callback_token] => 61A7
[oauth_token] => 6aMcbRK5wMqHgZQsdfsd
[oauth_token_secret] => ro8AJxZ67sUDoiOTk8sl4V3js0uyof1uPJVB14asdfs
[oauth_callback_confirmed] => true
[oauth_signature_method] => HMAC-SHA1
[oauth_signature] => V9YcMDq2rP7OiZTK1k5kb/otMzA=
Here I am supposed to receive the Oauth Permanent access token, but instead I get a Invalid Oauth signature. I dont know what I am doing wrong. I use the same signaures to sign the request. Should I sign the request using the new token and secret? I tried that as well but to no avail. I even tried implementing this in java using signpost library and got stuck at the exact same place. Help Help!!
The callback_token was something Yammer introduced in response to an OAuth security advisory earlier this year. When OAuth 1.0a was released, it was instead named oauth_verifier. However, it's not unlikely that Yammer still supports their workaround but rename it and try again to be sure.
Also, the below is information from the Yammer Development Network yesterday:
Tomorrow we will be releasing some
changes to the Yammer API to
facilitate user network switching on
API clients. Most of the change is in
the OAuth Access Tokens call which
allows you to generate pre-authorized
OAuth access tokens for a given user.
One token will be generated for each
network they are in and your clients
switch networks by sending an API
request signed with the appropriate
token for that network.
I'm assuming that Yammer OAuth libraries might need to be updated per this change. I haven't taken a look at it yet.
Edit: My python-yammer-oauth library still works despite Yammer having changed things on their side.
Edit2: Could you try using signature method PLAINTEXT instead of HMAC-SHA1? I've had problems with Yammer and HMAC-SHA1.
I tried by using PLAINTEXT.. but for this method its giving me the same "Invalid OAuth signature" error even for requesting the token.
So is it possible to generate the access token we use HMAC-SHA1 and for accessing the actual API method i.e. for posting the message.. we use PLAINTEXT?
just found the problem!
I had forgotten to add an ampersand ("&") at the end of CONSUMER_SECRET. Perhaps this is your issue as well?