Showing posts with label gmail API. Show all posts
Showing posts with label gmail API. Show all posts

Thursday, December 5, 2019

What is refresh token? How to retrieve google refresh token? What is the expiration time?

Refresh Token:

Refresh tokens are the credentials that can be used to acquire new access tokens. The lifetime of a refresh token is much longer compared to the lifetime of an access token. When current access tokens expire or become invalid, the authorization server provides refresh tokens to the client to obtain new access token.

Resource Link: https://www.tutorialspoint.com/oauth2.0/refresh_token.htm

I have also got a full blog post here: Google Refresh Tokens : Answers to Some Common Questions  It is really awesome. So I keep it in my blog as it is. So that I can read it again.

Google refresh tokens are used to generate an access token, even when the user is not available at the browser (the user is "offline"). Web applications typically save the refresh token of the user when he authorizes the Google application. The application can later use this refresh token to generate an access token, and make API calls on behalf of the user directly from the server.
The most popular use of a refresh token is during the execution of a cron job at the server. For example, a cron script would use the refresh token to generate a Google Analytics report for the user at a specific time.
Typically developers have some questions over the usage of Google refresh tokens. This article contains some of the common questions asked.

I got a refresh token previously, but now Google stopped sending refresh token

For the first time when the user authorizes your application he will see a consent screen. Through the consent screen he allows the application to get access to his data via API calls. Typically after the first time, user will not see a consent screen.
It is through this consent screen, you get a refresh token. No consent screen means no refresh token.
To force the application to show a consent screen, set prompt=consent in the Google OAuth url. This will ensure that Google returns a refresh token.
https://accounts.google.com/o/oauth2/v2/auth?
client_id=client_id&
scope=API_SCOPE&
redirect_uri=REDIRECT_URL&
response_type=code&
access_type=offline&
prompt=consent

I got a new refresh token. Does it mean that my older refresh token will not work ?

The older refresh token will work too. However Google imposes a limit of 50 refresh tokens per user for each application. If this limit is reached, creating a new token automatically will invalidate the oldest token without warning.
This means that for the first 50 times, you will get a new refresh token, and all the 50 refresh tokens will work.
However when the 51st refresh token comes, the first refresh token becomes invalidated. The 52nd refresh token will invalidate the 2nd refresh token. And so on.
Also the limit of 50 is not a fixed one. For Google Analytics API is is set to 25. The exact limit can be found in the documentation of the API. The documentation of each Google API typically has a section "Authorization". In this section, you can find the exact limit. If the limit is not listed, it is safe to consider it as 50.
In general it is not a good idea to request a refresh token each time when the user logs in. A refresh token is returned each time when the Google OAuth url contains the parameter prompt=consent. Setting prompt=none would not return a refresh token.
In the worst case, when your application is forced to get a new refresh token each time, make sure that your application is saving the latest refresh token, and removing the older refresh token.

When does a refresh token expire ?

Refresh tokens do not expire, unless there are few special conditions :
  1. The user has removed your Google application.
  2. The refresh token has not been used for six months.
  3. The user changed password and the refresh token contained Gmail scopes.
    This means that the refresh token will be invalidated only when he had previously given the permisions for managing his Gmail, and then later changed his password.
    For the rest of Google services like Youtube, Calendar etc, a changed password will not invalidate the refresh token.
  4. The application generated a new refresh token for the user for more than 50 times.
    See the above question I got a new refresh token. Does it mean that my older refresh token will not work for more information.

Is it a good idea to get a new refresh token from the user every time he logs-in to my Google application ?

No. As discussed above there is a limit of 50 refresh tokens for each user. This does not mean that Google will not return a refresh token after the 50th API call. A refresh token will be returned, but the older refresh token will be invalidated. See the question I got a new refresh token. Does it mean that my older refresh token will not work for more information on this.

How can we test google oauth2 using curl?

Answer is available in this link with full description:

https://github.com/jhanley-com/google-oauth-2-0-testing-with-curl

What is Access Token, ID Token? How can we retreive User info from Access Token or ID Token?

What is an Access Token?
An Access token is a Bearer token that you will have to add in all request headers to be authenticated as a concrete user.

Resource Link: https://stackoverflow.com/questions/25838183/what-is-the-oauth-2-0-bearer-token-exactly/25843058

What is an ID Token?


An ID Token is a JWT (JSON Web Token), that is, a cryptographically signed Base64-encoded JSON object. Normally, it is critical that you validate an ID token before you use it, but since you are communicating directly with Google over an intermediary-free HTTPS channel and using your client secret to authenticate yourself to Google, you can be confident that the token you receive really comes from Google and is valid. If your server passes the ID token to other components of your app, it is extremely important that the other components validate the token before using it.

Since most API libraries combine the validation with the work of decoding the base64 and parsing the JSON, you will probably end up validating the token anyway as you access the fields in the ID token.

An ID token's payload
An ID token is a JSON object containing a set of name/value pairs. Here’s an example, formatted for readability:

{
  "iss": "accounts.google.com",
  "at_hash": "HK6E_P6Dh8Y93mRNtsDB1Q",
  "email_verified": "true",
  "sub": "10769150350006150715113082367",
  "azp": "1234987819200.apps.googleusercontent.com",
  "email": "jsmith@example.com",
  "aud": "1234987819200.apps.googleusercontent.com",
  "iat": 1353601026,
  "exp": 1353604926,
  "nonce": "0394852-3190485-2490358",
  "hd": "example.com"
}

Resource Link: https://developers.google.com/identity/protocols/OpenIDConnect#obtainuserinfo

How can we retreive User info from Access Token or ID Token?

Answer is available in this link: https://www.oauth.com/oauth2-servers/signing-in-with-google/verifying-the-user-info/

Resource Link:

  1. https://stackoverflow.com/questions/16501895/how-do-i-get-user-profile-using-google-access-token
  2. https://stackoverflow.com/questions/22516693/how-to-get-user-profile-on-google-api-using-the-java-library

Sunday, December 3, 2017

Is Java GMail API thread-safe?

Question:

In particular, can multiple threads use the same GMail service instance?

Answer:

Nope. Gmail implementation is not thread-safe.
Therefore, if you are running as a multi-threaded application, each thread that you are making requests from must have its own instance of httplib2.Http().
Resource Link: gmail api service

Sunday, November 19, 2017

Is Java GMail API thread-safe?

Nope. Gmail implementation is not thread-safe.
Therefore, if you are running as a multi-threaded application, each thread that you are making requests from must have its own instance of httplib2.Http().
Resource Link: gmail api service
Original Link: https://stackoverflow.com/a/37193685/2293534

How to get access token using gmail api?

How to get access token using gmail api?
Ans: If you are using OAuth 2.0. So there is a basic pattern for accessing a Google API using OAuth 2.0. It follows 4 steps:
  1. Obtain OAuth 2.0 credentials from the Google Developers Console.
  2. Obtain an access token from the Google Authorization Server.
  3. Send the access token to an API.
  4. Refresh the access token, if necessary.
For details, you can follow the tutorial - Using OAuth 2.0 to Access Google APIs
You have to visit the Google Developers Console to obtain OAuth 2.0 credentials such as a client ID and client secret that are known to both Google and your application

Root Cause Analysis:

Issue-1:
After studying your code, some lacking are found. If your code runs smoothly, then the code always give an empty string. Because your AccessToken() method always return return "";
Issue-2:
 catch (Exception e)
    {
        System.out.println("Error.");
    }
Your try catch block is going exception block. Because, it seems that you have not completed your code properly. You have missed encoding as well as using JSONObject which prepares the access token. So it is giving output as
Error.

Solution:

I got that your code is similar with this tutorial
As your code needs more changes to solve your issue. So I offer you to use LinkedHashMap or ArrayList. Those will provide easier way to make solution. So I give you 2 sample code to make your life easier. You can choose any of them. You need to change refresh_token, client id, client secret and grant type as yours.
private String getAccessToken()
{
    try
    {
        Map<String,Object> params = new LinkedHashMap<>();
        params.put("grant_type","refresh_token");
        params.put("client_id",[YOUR CLIENT ID]);
        params.put("client_secret",[YOUR CLIENT SECRET]);
        params.put("refresh_token",[YOUR REFRESH TOKEN]);

        StringBuilder postData = new StringBuilder();
        for(Map.Entry<String,Object> param : params.entrySet())
        {
            if(postData.length() != 0)
            {
                postData.append('&');
            }
            postData.append(URLEncoder.encode(param.getKey(),"UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()),"UTF-8"));
        }
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        URL url = new URL("https://accounts.google.com/o/oauth2/token");
        HttpURLConnection con = (HttpURLConnection)url.openConnection();
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setRequestMethod("POST");
        con.getOutputStream().write(postDataBytes);

        BufferedReader  reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        StringBuffer buffer = new StringBuffer();
        for (String line = reader.readLine(); line != null; line = reader.readLine())
        {
            buffer.append(line);
        }

        JSONObject json = new JSONObject(buffer.toString());
        String accessToken = json.getString("access_token");
        return accessToken;
    }
    catch (Exception ex)
    {
        ex.printStackTrace(); 
    }
    return null;
}
For accessing google play android developer api, you need to pass the previous refresh token to get access token
private String getAccessToken(String refreshToken){

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
try 
{
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
    nameValuePairs.add(new BasicNameValuePair("grant_type",    "refresh_token"));
    nameValuePairs.add(new BasicNameValuePair("client_id",     GOOGLE_CLIENT_ID));
    nameValuePairs.add(new BasicNameValuePair("client_secret", GOOGLE_CLIENT_SECRET));
    nameValuePairs.add(new BasicNameValuePair("refresh_token", refreshToken));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    org.apache.http.HttpResponse response = client.execute(post);
    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer buffer = new StringBuffer();
    for (String line = reader.readLine(); line != null; line = reader.readLine())
    {
        buffer.append(line);
    }

    JSONObject json = new JSONObject(buffer.toString());
    String accessToken = json.getString("access_token");

    return accessToken;

}
catch (IOException e) { e.printStackTrace(); }

return null;
}

Resource Link:

Hope that, this samples and resource link will help you to solve your issue and get access of access token.

What is 400 bad request?

Ans: It indicates that the query was invalid. Parent ID was missing or the combination of dimensions or metrics requested was not valid.
Recommended Action: You need to make changes to the API query in order for it to work.
For HTTP/1.1 400 Bad Request error, you can go through my another answer. It will help you to make sense about which host you need to use and which conditions you need to apply.

Why token expires? What is the limit of token?

A token might stop working for one of these reasons:
  1. The user has revoked access.
  2. The token has not been used for six months.
  3. The user changed passwords and the token contains Gmail, Calendar, Contacts, or Hangouts scopes.
  4. The user account has exceeded a certain number of token requests.
There is currently a limit of 25 refresh tokens per user account per client. If the limit is reached, creating a new token automatically invalidates the oldest token without warning. This limit does not apply to service accounts.

Which precautions should be followed?

Precautions - 1:

Some requests require an authentication step where the user logs in with their Google account. After logging in, the user is asked whether they are willing to grant the permissions that your application is requesting. This process is called user consent.
If the user grants the permission, the Google Authorization Server sends your application an access token (or an authorization code that your application can use to obtain an access token). If the user does not grant the permission, the server returns an error.

Precautions - 2:

If an access token is issued for the Google+ API, it does not grant access to the Google Contacts API. You can, however, send that access token to the Google+ API multiple times for similar operations.

Precautions - 3:

An access token typically has an expiration date of 1 hour, after which you will get an error if you try to use it. Google Credential takes care of automatically "refreshing" the token, which simply means getting a new access token.
Save refresh tokens in secure long-term storage and continue to use them as long as they remain valid. Limits apply to the number of refresh tokens that are issued per client-user combination, and per user across all clients, and these limits are different. If your application requests enough refresh tokens to go over one of the limits, older refresh tokens stop working.
Resource Link: https://stackoverflow.com/a/36266696/2293534