Search code examples
.netoauth-2.0google-tasks-api

Google / OAuth 2 - Automatic logon


I'm playing a bit with OAuth 2.0 in combination with some Google API. Although the authorization process is quite easy, I'm facing a problem with the automatic authorization after the initial authorization has been completed.

So:

1. Authorization is done for the first time. (user grants access, I get the token etc etc)
2. User exits the application
3. User starts the application again
4. How to logon automatically here?

At point 4, I do have a refresh_token so I should just request a new token using that request_token. But I still keep getting 401 Unauthorized results on my calls.

So what I try to do is that my application can logon silently so that the user doesn't have to grant access every time.


Solution

  • You should be able to refresh OAuth 2.0 token using the following request:

    POST /o/oauth2/token HTTP/1.1
    Host: accounts.google.com
    Content-Type: application/x-www-form-urlencoded
    
    client_id=21302922996.apps.googleusercontent.com&
    client_secret=XTHhXh1SlUNgvyWGwDk1EjXB&
    refresh_token=1/6BMfW9j53gdGImsixUH6kU5RsR4zwI9lUVX-tqf8JXQ&
    grant_type=refresh_token
    

    As pointed in Google OAuth 2.0 documentation.

    I just tried it out using curl and it works as expected:

    curl -d client_id=$CLIENT_ID -d client_secret=$CLIENT_SECRET -d refresh_token=$REFRESH_TOKEN -d grant_type=refresh_token https://accounts.google.com/o/oauth2/token
    
    {"access_token":"$ACCESS_TOKEN","token_type":"Bearer","expires_in":3600}