Question

I would like to write integration tests for all of my service methods. These methods are secured using OAuth2, and the iOS client is using gtm-oauth2 library.

What's some code that I can write to obtain an access token using username/password credentials from within an OCUnit test case?

Can anyone who has done this save me the time trawling through Google code?

Was it helpful?

Solution

It's a three stage process.

First, forget about usernames and passwords. They will lead you in the wrong direction.

At some offline point, you will need to generate a refresh token. This will require a browser session as Google will walk the user through an authorisation dialogue. Once you have the refresh token you can save it or embed it in your test harness (assuming that this is a dummy user with no secrets worth protecting. You can think of the refresh token as the oauth equivalent of username and password if you like.

Now in your test setup, you will use the refresh token to request an access token. That is a simple call to

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
refresh_token=1/6BMfW9j53gdGImsiyUH5kU5RsR4zwI9lUVX-tqf8JXQ&
grant_type=refresh_token

As long as the user has not revoked the access granted to your application, the response includes a new access token. A response from such a request is shown below:

{
  "access_token":"1/fFBGRNJru1FQd44AzqT3Zg",
  "expires_in":3920,
  "token_type":"Bearer",
}

These details are taken from https://developers.google.com/accounts/docs/OAuth2WebServer#offline

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top