Google People API unauthorized - google-people-api

I want to get my own Google Contacts so I read up on the People API documentation, on the "Authorize Request" section under the "Acquiring and using an API key" it says:
API keys: A request that does not provide an OAuth 2.0 token must send
an API key. The key identifies your project and provides API access,
quota, and reports.
The API supports several types of restrictions on API keys. If the API
key that you need doesn't already exist, then create an API key in the
Console by clicking Create credentials > API key. You can restrict the
key before using it in production by clicking Restrict key and
selecting one of the Restrictions.
So that seems easy enough, I went to the project page and created an unrestricted API Key, then I can create this request URL: https://people.googleapis.com/v1/people/me?key=API_KEY&personFields=names, with the API key just in the URL, as this statement suggest.
After you have an API key, your application can append the query parameter key=yourAPIKey to all request URLs.
But when I run the URL I posted before it returns this:
{
"error": {
"code": 401,
"message": "The request does not have valid authentication credentials.",
"status": "UNAUTHENTICATED"
}
}
What am I doing wrong? :(

Turns out the solution is pretty simple and I feel quite stupid, it isn't possible to access your own Google Contacts or any other private data using the API key, if you're trying to access any private data you should use OAuth 2.0 and not an API key (unlike for instance a public YouTube play-list where you CAN use an API key). Thanks to #Mateo Randwolf

Related

Auth to google API with API-Key instead of OAuth 2.0

in https://developers.google.com/calendar/api/v3/reference/calendarList/list?apix=true#auth
I can see, that I can use OAuth2 and API-Key to authenticate for the calendarList endpoints
My first test with postman and OAuth2 works perfect: I get the JSON List of all calendars of the autheticated user
Now I test the entpoint with authentication over API-Key
I create the API-Key and enabled the calendar for this api key:
Problem:
I've tested it with postman and Auth-Type=ApiKey and with Parameter key=MYAPIKEY but always get error 401 "Request is missing required authentication credential"
Does anyone have a (postman) example to access the google calendard api with an API-Key?
API keys are only used to access public data not private user data.
In order to use an api key with postman you would simply take the rquest and add key=YourKEY on the end
The following is a good example of this but unfortunately there is currently an issue with API keys and public calendars. Requiring authorization instead of just an api key194427607
https://www.googleapis.com/calendar/v3/calendars/en.danish%23holiday%40group.v.calendar.google.com?key=[YOUR_API_KEY]
You are not going to be able to use calendar list without being authorized calendarlist.list states in the documentation that you must be authorized as its private user data.

In AWS how do I add an API key to my API?

Hello: I've been following two tutorials in the AWS documentation:
creating the sample pet store API (https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-from-example.html)
...and creating an API key (https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-setup-api-key-with-console.html#api-gateway-usage-plan-create-apikey).
When I test the pet store get method with the provided URL, it returns:
Welcome to your Pet Store API You have successfully deployed your
first API. You are seeing this HTML page because the GET method to the
root resource of your API returns this content as a Mock integration.
The Pet Store API contains the /pets and /pets/{petId} resources. By
making a GET request to /pets you can retrieve a list of Pets in your
API. If you are looking for a specific pet, for example the pet with
ID 1, you can make a GET request to /pets/1.
You can use a REST client such as Postman to test the POST methods in
your API to create a new pet. Use the sample body below to send the
POST request:
{
"type" : "cat",
"price" : 123.11 }
Now I go to the API Gateway -> API -> Resources -> -> Method Request -> API Key Required and change it to "True" and redeploy.
When I go to the provided URL to test, now the page returns:
{"message":"Forbidden"}
Which makes sense... I told it API required = true, right?
So my question is, how do I pass the API key? So that I don't get the "forbidden" result? I didn't see that in the tutorial links I pasted above and haven't been able to find elsewhere.
You Create a Usage Plans
Attach this usage plan to your API and Stage
Create an API Key
Now invoke your API with header named x-api-key and value of it is the API Key created in step-3
Sample:
curl -i -H "x-api-key: Cd2YiWs8Fv8Lg6njI0wXf1iiNOE94XjM3EQe8567" -X GET https://7r9cvghbf4.execute-api.ap-northeast-2.amazonaws.com/dd/pets
Assuming you've followed all steps for creating the API key you can use this API key by specifying it in the x-api-key header within your request.
You distribute API keys to your customers and require them to pass the API key as the X-API-Key header of each incoming request.
More information for using API keys in API Gateway is available on: Choose an API key source - Amazon API Gateway

Where do I get Client Secret for Google Admin SDK?

This documentation: https://developers.google.com/admin-sdk/directory/v1/quickstart/quickstart-java#step_1_enable_the_admin_sdk_directory_api
Mentions that I need to have client secret, and the code sample lower on that page uses client secret.
However, when i go to APIs and auth/Credentials here https://console.developers.google.com/project/[proj]/apiui/credential#
I only can find clientId and private key instead.
Is there some other place I should get client secret from?
Google API Console is here
APIs and Auth (left)
Credentials Submenu
After I created an OAuth, my information was there.
(by my information was there, I mean successful showing of client secret, etc)
I used wrong type of API, I need web API for that, but I used server API when I was setting up Authentication. Adding web API for authentication added client secret for me.

Facebook open graph - what is session secret and how to find it?

can someone please enlighten me on what session secret is and how to find it?
A session secret key is used for signing request to Facebook api functions. It is used in situations where it can be disclosed, for example in browser executed javascript code which makes API calls and needs to sign them.
Facebook have not yet provided a way to get a session secret key in the new graph API so you need to enable 'deprecated api methods' under your app settings and then you can use the old REST api call auth.promoteSession to get your session secret key server-side, then embed that key in the code to be used client-side.

How can I verify a Google authentication API access token?

How can I verify a Google authentication access token?
I need to somehow query Google and ask: Is [given access token] valid for the [example#example.com] Google account?
Short version
It's clear how an access token supplied through the Google Authentication Api :: OAuth Authentication for Web Applications can be used to then request data from a range of Google services. It is not clear how to check if a given access token is valid for a given Google account. I'd like to know how.
Long version
I'm developing an API that uses token-based authentication. A token will be returned upon provision of a valid username+password or upon provision of a third-party token from any one of N verifiable services.
One of the third-party services will be Google, allowing a user to authenticate against my service using their Google account. This will later be extended to include Yahoo accounts, trusted OpenID providers and so on.
Schematic example of Google-based access:
The 'API' entity is under my full control. The 'public interface' entity is any web- or desktop-based app. Some public interfaces are under my control, others will not be and others still I may never even know about.
Therefore I cannot trust the token supplied to the API in step 3. This will be supplied along with the corresponding Google account email address.
I need to somehow query Google and ask: Is this access token valid for example#example.com?
In this case, example#example.com is the Google account unique identifier - the email address someone uses to log in to their Google account. This cannot be assumed to be a Gmail address - someone can have a Google account without having a Gmail account.
The Google documentation clearly states how, with an access token, data can be retrieved from a number of Google services. Nothing seems to state how you can check if a given access token is valid in the first place.
Update
The token is valid for N Google services. I can't try a token against a Google service as means of verifying it as I won't know which subset of all Google's services a given user actually uses.
Furthermore, I'll never be using the Google authentication access token to access any Google services, merely as a means of verifying a supposed Google user actually is who they say they are. If there is another way of doing this I'm happy to try.
For user check, just post
get the access token as accessToken and post it and get the response
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=accessToken
you can try in address bar in browsers too, use httppost and response in java also
response will be like
{
"issued_to": "xxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
"audience": "xxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
"user_id": "xxxxxxxxxxxxxxxxxxxxxxx",
"scope": "https://www.googleapis.com/auth/userinfo.profile https://gdata.youtube.com",
"expires_in": 3340,
"access_type": "offline"
}
The scope is the given permission of the accessToken. you can check the scope ids in this link
Update:
New API
post as below
https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123
Response will be as
{
// These six fields are included in all Google ID Tokens.
"iss": "https://accounts.google.com",
"sub": "110169484474386276334",
"azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"iat": "1433978353",
"exp": "1433981953",
// These seven fields are only included when the user has granted the "profile" and
// "email" OAuth scopes to the application.
"email": "testuser#gmail.com",
"email_verified": "true",
"name" : "Test User",
"picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
"given_name": "Test",
"family_name": "User",
"locale": "en"
}
For more info, https://developers.google.com/identity/sign-in/android/backend-auth
Ok, most answers are valid but not quite right. The idea of JWT is that you can validate the token without the need to contact the issuer everytime. You must check the id and verify the signature of the token with the known public key of the certificate google used to sign the token.
See the next post why and how to do this.
http://ncona.com/2015/02/consuming-a-google-id-token-from-a-server/
you can verify a Google authentication access token by using this endpoint:
https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=<access_token>
This is Google V3 OAuth AccessToken validating endpoint, you can refer from google document below: (In OAUTH 2.0 ENDPOINTS Tab)
https://developers.google.com/identity/protocols/OAuth2UserAgent#validate-access-token
function authenticate_google_OAuthtoken($user_id)
{
$access_token = google_get_user_token($user_id); // get existing token from DB
$redirecturl = $Google_Permissions->redirecturl;
$client_id = $Google_Permissions->client_id;
$client_secret = $Google_Permissions->client_secret;
$redirect_uri = $Google_Permissions->redirect_uri;
$max_results = $Google_Permissions->max_results;
$url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.$access_token;
$response_contacts = curl_get_responce_contents($url);
$response = (json_decode($response_contacts));
if(isset($response->issued_to))
{
return true;
}
else if(isset($response->error))
{
return false;
}
}
Use the below endpoint to get user info such as name, email, photo etc.
https://www.googleapis.com/oauth2/v3/userinfo?access_token=<access token>
Use the below endpoint to get token info, such as expiry time, token scope etc.
https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=<access token>
Google oauth code flow response in addition to access_token also returns id_token that contains useful for validation info in encrypted form.
One thing that makes ID tokens useful is that fact that you can pass
them around different components of your app. These components can use
an ID token as a lightweight authentication mechanism authenticating
the app and the user. But before you can use the information in the ID
token or rely on it as an assertion that the user has authenticated,
you must validate it.
Validation of an ID token requires several steps:
Verify that the ID token is a JWT which is properly signed with an appropriate Google public key.
Verify that the value of aud in the ID token is equal to your app’s client ID.
Verify that the value of iss in the ID token is equal to accounts.google.com or https://accounts.google.com.
Verify that the expiry time (exp) of the ID token has not passed.
If you passed a hd parameter in the request, verify that the ID token has a hd claim that matches your Google Apps hosted domain.
https://developers.google.com/identity/protocols/OpenIDConnect#validatinganidtoken link has code samples for validation of ID tokens.
See also https://security.stackexchange.com/questions/37818/why-use-openid-connect-instead-of-plain-oauth.
As per Google's documentation, you should use Google's AP Client Library that makes this (token verification, claim extraction etc.) much easier than writing your own custom code.
From a performance perspective, the token should be parsed locally without making a call to Google again. Off-course Google's public key is needed and retrieval of that key is done using a caching strategy, implemented in the Google's client library from #1 above.
FYI only. Google also uses a JWT token. See image below for reference.
Here's an example using Guzzle:
/**
* #param string $accessToken JSON-encoded access token as returned by \Google_Client->getAccessToken() or raw access token
* #return array|false False if token is invalid or array in the form
*
* array (
* 'issued_to' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
* 'audience' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
* 'scope' => 'https://www.googleapis.com/auth/calendar',
* 'expires_in' => 3350,
* 'access_type' => 'offline',
* )
*/
public static function tokenInfo($accessToken) {
if(!strlen($accessToken)) {
return false;
}
if($accessToken[0] === '{') {
$accessToken = json_decode($accessToken)->access_token;
}
$guzzle = new \GuzzleHttp\Client();
try {
$resp = $guzzle->get('https://www.googleapis.com/oauth2/v1/tokeninfo', [
'query' => ['access_token' => $accessToken],
]);
} catch(ClientException $ex) {
return false;
}
return $resp->json();
}
I need to somehow query Google and ask: Is this access token valid for example#example.com?
No. All you need is request standard login with Federated Login for Google Account Users from your API domain. And only after that you could compare "persistent user ID" with one you have from 'public interface'.
The value of realm is used on the Google Federated Login page to identify the requesting site to the user. It is also used to determine the value of the persistent user ID returned by Google.
So you need be from same domain as 'public interface'.
And do not forget that user needs to be sure that your API could be trusted ;) So Google will ask user if it allows you to check for his identity.
Try making an OAuth-authenticated request using your token to https://www.google.com/accounts/AuthSubTokenInfo. This is only documented to work for AuthSub, but it works for OAuth too. It won't tell you which user the token is for, but it will tell you which services it's valid for, and the request will fail if the token is invalid or has been revoked.
An arbitrary OAuth access token can't be used for authentication, because the meaning of the token is outside of the OAuth Core spec. It could be intended for a single use or narrow expiration window, or it could provide access which the user doesn't want to give. It's also opaque, and the OAuth consumer which obtained it might never have seen any type of user identifier.
An OAuth service provider and one or more consumers could easily use OAuth to provide a verifiable authentication token, and there are proposals and ideas to do this out there, but an arbitrary service provider speaking only OAuth Core can't provide this without other co-ordination with a consumer. The Google-specific AuthSubTokenInfo REST method, along with the user's identifier, is close, but it isn't suitable, either, since it could invalidate the token, or the token could be expired.
If your Google ID is an OpenId identifier, and your 'public interface' is either a web app or can call up the user's browser, then you should probably use Google's OpenID OP.
OpenID consists of just sending the user to the OP and getting a signed assertion back. The interaction is solely for the benefit of the RP. There is no long-lived token or other user-specific handle which could be used to indicate that a RP has successfully authenticated a user with an OP.
One way to verify a previous authentication against an OpenID identifier is to just perform authentication again, assuming the same user-agent is being used. The OP should be able to return a positive assertion without user interaction (by verifying a cookie or client cert, for example). The OP is free to require another user interaction, and probably will if the authentication request is coming from another domain (my OP gives me the option to re-authenticate this particular RP without interacting in the future). And in Google's case, the UI that the user went through to get the OAuth token might not use the same session identifier, so the user will have to re-authenticate. But in any case, you'll be able to assert the identity.
Check below URL. It works well. Its official document from Google itself.
Using one of the Google API Client Libraries (e.g. Java, Node.js, PHP, Python) is the recommended way to validate Google ID tokens.
https://developers.google.com/identity/sign-in/android/backend-auth#using-a-google-api-client-library