Detect revoked permission for App in Google API - oauth

I am using the PHP Google client library. I successfully get a token and refresh token from user/google to use with the API.
As soon as the user revokes the permission for my website in Googles settings on the Google page i get following error:
Error calling GET https://www.googleapis.com/calendar/v3/users/me/calendarList: (401) Invalid Credentials
That is expected behavior since the user revoked my permission.
However, how do I detect that a user revoked that access?
Currently i do the following to see if i have access:
//$token json fetched from database
$gclient->setAccessToken($token);
if ($gclient->getAccessToken())
//i should have access
Well this code unfortunately does not detect the revoked permission. How can i handle that?

Once you have detected that the user has revoked the permission you can ask the user to grant the permission again.
To detect that the grant has been revoked: Provided that you had authorization before,
Making an API call using a revoked access_token will result in a response with status code 401. Like this
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
Attempting to refresh a token after the revocation will result in a response with a 400 status code and an invalid_grant message. Just as specified in the RFC 6749, Section 5.2
invalid_grant The provided authorization grant (e.g., authorization
code, resource owner credentials) or refresh token is
invalid, expired, revoked, does not match the redirection
URI used in the authorization request, or was issued to
another client.
Here is an example of such response:
```lang-js
{
"error" : "invalid_grant"
}
```

Google APIs should only return 401 for lack of authorization. Since you had authorization before, receiving a 401 is a reliable indication that the user has revoked access.
Are you looking for a detection mechanism that notifies you of such changes before you make the API call? Today there is not a push notification mechanism from Google that can inform your application of such events. Of course, a pull-based mechanism is not useful -- you can simply make the API call and handle the 401 more efficiently.

Related

Google Calendar api authentication via POST request

I am trying to issue a POST request towards the google calendar api, but I fail to understand how to authenticate it.
I took the following steps to try and use a service account to do so:
I've enabled the the calendar api in the Google Cloud console
I've created a new service account, enabled G Suite Domain-wide Delegation, and downloaded the provided key.
I've added the service account email to the calendar to be able to make changes and create events.
I've tried to create a POST request to https://www.googleapis.com/calendar/v3/calendars/calendarId/events with the contents of the JSON key as the value of the Authorization header, but I receive the following error:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
Am I missing some steps or have I do not understand correctly the authentication process?
I would appreciate your help.
Its not simply a matter of applying the contents of the key file to your call, all google apis need an access token in order to authenticate them.
To get an access token from a service account you need to follow the following steps. Preparing to make an authorized API call
There are steps you will need to complete inorder to get the access token you will need to make a call to the api
After you obtain the client ID and private key from the API Console, your application needs to complete the following steps:
Create a JSON Web Token (JWT, pronounced, "jot") which includes a header, a claim set, and a signature.
Request an access token from the Google OAuth 2.0 Authorization Server.
Handle the JSON response that the Authorization Server returns.
I recommend you pick your favorite server sided programming language and find a client library for it. It will make things much easier then you trying to authncate using a service account by yourself.

Fetch auditDetails of YouTube channel

I am trying to fetch auditDetails of YouTube channels.
As per official API docs (https://developers.google.com/youtube/v3/docs/channels/list) I am supposed to provide an authorization token that contains the https://www.googleapis.com/auth/youtubepartner-channel-audit scope.
Authorization
A request that retrieves the auditDetails part for a channel resource must provide an authorization token that contains the https://www.googleapis.com/auth/youtubepartner-channel-audit scope. In addition, any token that uses that scope must be revoked when the MCN decides to accept or reject the channel or within two weeks of the date that the token was issued.
I am currently trying to fetch a YouTube channel's auditDetails by hitting following URL:
https://www.googleapis.com/youtube/v3/channels?key=xxxxxxxxxx&id=UC9eSXrzVl9ZFLwsNSBgvTog&part=auditDetails
But, it is returning an Insufficient Permission error as follows:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
Can someone suggest me an approach to generate youtubepartner-channel-audit scope for various YouTube channels.
The error you have encountered means that:
The OAuth 2.0 token provided for the request specifies scopes that are
insufficient for accessing the requested data.
You can request for authorization of auditDetails part for channel resource:
Must provide an authorization token that contains the
https://www.googleapis.com/auth/youtubepartner-channel-audit scope. In
addition, any token that uses that scope must be revoked when the MCN
decides to accept or reject the channel or within two weeks of the
date that the token was issued.
After that, you can add your scope to the OAuth sign-in request.
In order to introduce scopes, an authorization token containing those scopes needs to be created.
Authorization credentials can be created via the Credentials page in the API Console.
Create credentials
But before creating OAuth client ID authorization credentials, user is required to set a product name on the consent screen.
On the consent screen itself user can add multiple scopes as per application requirement.
Add scope

Invalid Access Token in FitBit

i'm trying to integrate the Fitbit SDK in my iOS app. I have created project on fitbit now i'm running there API in Postman to check profile, but in response it is showing me invalid access token,
{
"errors": [
{
"errorType": "invalid_token",
"message": "Access token invalid: 39ec7defa6f0e33b314bbf6217279b15. Visit https://dev.fitbit.com/docs/oauth2 for more information on the Fitbit Web API authorization process."
}
],
"success": false
}
This is my API https://api.fitbit.com/1/user/-/profile.json and this is what i'm passing in header, Authorization : Bearer Client Secret But it is showing me status code 401 having error of invalid access token . How can i get the access token for my app?
You need to get an OAuth2.0 token from the FitBit authentication service before you can call any other endpoints on the API. You will need to redirect your app to Safari and go to the fitbit authentication service so that the user can log in and authorise your apps access to their FitBit data. The callback will then return an OAuth token that you can pass in subsequent requests.
You will need to call something like this:
https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=%#&scope=%#&redirect_uri=%#"
This is the official fitbit documentation for Authorisation:
https://dev.fitbit.com/build/reference/web-api/oauth2/

Microsoft Graph API BadRequest Current authenticated context is not valid

I am trying to develop a simple background app to connect to my onedrive account (work) and regularly download some files.
I followed this tutorial https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols-oauth-client-creds
I have registered the app here https://apps.dev.microsoft.com/portal/register-app
I have written down the client_id and client_secret
To get an access token I make a POST request to
https://login.microsoftonline.com/common/oauth2/v2.0/token
with the following form encoded data
{
'client_id': 'clientid here',
'client_secret': 'secret is here',
'scope': 'https://graph.microsoft.com/.default',
'grant_type': 'client_credentials',
}
I get back an access_token
{'ext_expires_in': 0,
'token_type': 'Bearer',
'expires_in': 3600,
'access_token': 'eyJ0eXAiOiJKV1QiLCJhbGciO---SHORTENED FOR BREVITY'}
Next I make a GET request (with Bearer header properly set) to https://graph.microsoft.com/v1.0/me
and get this eror response (which I get for any endpoint fwiw)
{
"error": {
"code": "BadRequest",
"message": "Current authenticated context is not valid for this request",
"innerError": {
"request-id": "91059f7d-c798-42a1-b3f7-2487f094486b",
"date": "2017-08-05T12:40:33"
}
}
}
I have these permissions configured in the app setting
Any ideas what might be wrong?
I'll file a bug to improve this awful error message. The problem is that you are making a request using application permissions (client_credentials flow) - where there is no signed-in user context. Your request is to /me, and /me is basically an alias for the signed-in user - and in this case there isn't one!
You should try a call to https://graph.microsoft.com/v1.0/users instead. But, before you do that. In the app registration portal, you've selected delegated permissions, but you are calling with application permissions. You should remove the delegated permissions, and select the appropriate application permissions - to call users, select User.Read.All for example. Then make sure to consent/reconsent your app by going to the /adminconsent endpoint.
Please also read more on permissions and delegated and application permissions here: https://developer.microsoft.com/en-us/graph/docs/concepts/permissions_reference
Hope this helps,
i used https://graph.microsoft.com/v1.0/users/{{Emailid}}/messages to get all the messages in my inbox
In clientCredential flow you are accessing as an with Client secret or with client certificate . So Graph API no linger understands who is me. So you need use https://graph.microsoft.com/v1.0/users/<Your_userId> or https://graph.microsoft.com/v1.0/users/<your_userprincipalname>.
eg.https://graph.microsoft.com/v1.0/users/1sd1353as..
or
eg.https://graph.microsoft.com/v1.0/users/John_doe#contso.com
Reference: https://learn.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http

Passing OAUTH2 tokens from iOS to Rails

I have a Rails website that has Google OAUTH2 implemented and working.
We are developing an iOS app, which is going to talk to my web server using APIs. Some of the APIs need the user to be authenticated. The idea, is that the iOS app authenticates the user using OAUTH2 on the device, then POSTs the token over SSL from the device to the web as the authentication. I need the website to verify the token.
In the Google API console, I added the client ID for the iPhone device, and got an access token by going to:
https://accounts.google.com/o/oauth2/auth?
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&
redirect_uri=urn:ietf:wg:oauth:2.0:oob&
response_type=code&
client_id={my client id}
Then, I pass the token to my site. On my site, I validate the token via:
google = OmniAuth::Strategies::GoogleOauth2.new(ENV['GOOGLE_API_KEY'],['GOOGLE_CLIENT_API_SECRET'])
client = OAuth2::Client.new(ENV['GOOGLE_API_KEY'],['GOOGLE_CLIENT_API_SECRET'], google.options.client_options)
access_token = OAuth2::AccessToken.new(client, params[:token], google.options.access_token_options || {})
google.access_token = access_token
google.auth_hash
When I attempt to auth_hash, the following error is returned:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
From here, I have no clue why I have specified invalid credentials.
ENV['GOOGLE_API_KEY'] points to the same API key as the website, and ENV['GOOGLE_CLIENT_API_SECRET'] points to the secret for the iOS client.
The URL I used above, I thought, gave me an access token. In reality, it returns to me an authorization code (which can then be used to get an access token).
The solution, is to exchange the authorization code, for an access token, then I can pass the token around and use it.
The difference between an authorization code and an access token is somewhat vague on the Google site, but you can read about how to exchange them here:
https://developers.google.com/accounts/docs/OAuth2WebServer

Resources