API Conventions

OAuth

Authorization

Kiva uses OAuth 1.0a protocol to control application access to protected resources. OAuth is an industry standard that allows a user to authorize an application to act on their behalf with certain permissions. OAuth gives the user a great deal of control and security in that the application never has full access to their account, passwords, or other credentials and that the user can revoke the application's access to their account any time using their Kiva account preferences.

The mechanics of OAuth 1.0a are fairly simple:

  1. Decide what kind of API access your application needs (e.g. Read-only access for a lender account).
  2. Request a Request Token.
  3. Redirect the user to Kiva with the Request Token, requesting particular scope of permissions.
  4. Kiva will handle authenticating the user on Kiva.org and will confirm the access request by your application with the user.
  5. If the user approves this request, Kiva will redirect the user back to your application along with a code you can use to confirm the approval. In most cases, your application will exchange this code directly through Kiva for a long-lived Access Token you can use for API access.
  6. Your application can then make requests for protected resources via the Kiva API until the access token expires or until the user revokes your application's access.

The wonderful people at the Internet Engineering Task Force produced this beautiful diagram to explain an OAuth authorization flow:

Obtaining Request Tokens

The first step of the authentication is to obtain a request token from the request token endpoint.

POST https://api.kivaws.org/oauth/request_token
WARNING: You will end up in the seventh circle OAuth Authorization Header Hell if you try to construct the header yourself. Use a library: http://code.google.com/p/oauth/

The library you use must conform to the OAuth 1.0a standard and send all the required parameters in the OAuth 1.0a specification:

This method must be called via HTTPS using the POST method with parameters passed in the HTTP request body. The request must contain an OAuth 1.0a authorization header. Note the oauth_callback parameter is the one you entered when you configured your app on the developer dashbaord

If your request is successful the server will respond with a JSON object with the following properties:

  • oauth_token - The token identifier.
  • oauth_token_secret - The token key. This key should be protected securely as with all user private data.
  • oauth_callback_confirmed - This will always be set and always be true.

Let's consider an example. A website, Lender Web, wants to authenticate a user with Kiva.org to access their lending history via the Kiva API. To start the process, Lender Web requests a request token from Kiva. The request token response will look something like:

oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app&oauth_token_secret=26Lm-E.nZo-K0524BydRsmmv14Xk5QT5j.erCyZQh6&oauth_callback_confirmed=true

If your request is rejected you will be returned a standard OAuth 1.0a error response. Your request may be rejected for any number of reasons including:

  • Your Authorization header is incorrectly calculated, malformed, or corresponds to an invalid or restricted client.
  • Failure to use HTTPS for the request.
  • Missing or invalid parameters or any other errors in the construction of your POST request.

Choosing an Authorization Flow

Before digging deep into authentication mechanics it is important to first understand which type of user interaction flow is appropriate for the kind of application you are building. Typically, you'll be limited by the software or devices your application targets, but you may also make certain decisions based on the expectations or needs of your users. The flow you choose determines how your user is directed to Kiva.org to approve your app and how the user arrives back at your app to complete the authentication process.

The supported flows are:

  1. Browser Redirect: This flow is best for most web sites and browser-based applications as well as apps on devices where a modern browser is available, such as a smartphone, laptop, or desktop computer.
  2. Out of Band: This flow is best for software environments without a web browser or that restrict integration between web browsers and your application. Simple mobile devices, video game consoles, TVs and other connected devices may fall in this category. Additionally, some developers may find this flow simplest for users with limited exposure to technology.
  3. Embedded Browser: This is an alternative of the Browser Redirect flow for apps that prefer not to redirect a user outside of their application for authentication. To use this flow you must be able to embed a web browser view into your application.

Browser Redirect flow for Websites

Browser Redirect is the most natural flow for most websites to authenticate with Kiva. That's because this flow leverages the power of URL redirects supported by every web browser in existence. When your app is ready to authenticate the user you simply send the user to a URL on Kiva. You'll know authentication has completed when the user is directed back to your website via a specific callback URL you register with your application. You'll also receive an authentication code or an error code in the URL query string to let you know how the auth exchange turned out.

Lender Web then directs the user to Kiva, with the request token to Kiva using the URL:

https://www.kiva.org/oauth/authorize?client_id=org.lenderweb&response_type=code&oauth_callback=https%3A%2F%2Flenderweb.org%2Fkiva_oauth_callback&state=6ED1279AB3340E9&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app

At this point the user is directed to log in to Kiva and approve Lender Web for read-only access to private data in their account. If the user approves the app Kiva redirects the user to Lender Web using a HTTP redirect (status 303) to the callback URL pre-registered by Lender Web:

https://lenderweb.org/kiva_oauth_callback?oauth_verifier=dk202zas&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app&state=6ED1279AB3340E9

The Lender Web server can now make a quick check with the Kiva API to confirm the code *dk202zas* is valid and to claim an access token valid for API requests to fetch private user lending history. If the user had rejected the authorization request the user would have been redirect to Lender Web at the same endpoint, but with a different query string:

https://lenderweb.org/kiva_oauth_callback?error_code=access_denied&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app&state=6ED1279AB3340E9

Note that in either case a state parameter is preserved across the redirects so that Lender Web track exactly which user session it is being authenticated.

Browser Redirect flow for Devices

The Browser Redirect flow is a also convenient flow for native apps that run on devices where a modern browser is present. This includes popular desktop operating systems like Mac OS X & Windows and modern mobile operating systems like iOS & Android. In this scenario, URL redirects are used just as the flow between websites. The key difference is the local operating system brokers the redirects between your application and the user's web browser (rather than redirects being handled internally by the browser itself). In this flow a custom URL scheme is registered with the local OS and is used lieu of HTTPS in the Callback URL — this way the browser knows to redirect control back to your application rather than to a website as before.

Let’s imagine an example using an app, Lender App, designed to run on iOS devices. Like Lender Web this app wants to access lending history for a user and thus needs read-only access to private Kiva user data. Lender App starts the process by asking the local operating system to open a web page in the local browser, Safari. On iOS 4, the code looks like this:

hNSString* launchUrl = @"https://www.kiva.org/oauth/authorize?client_id=org.lenderweb.app&response_type=code&oauth_callback=x-application-org-lenderweb-app-iphone%3Akiva_oauth_callback&state=6ED1279AB3340E9&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app"; [[UIApplication sharedApplication] openURL:[NSURL URLWithString: launchUrl]];

Just as with the website example, the user must log in to Kiva and approve the application for read-only access to private data in their account. If access is approved, the Kiva redirects the user to the provided redirect URI with a new authentication code:

hx-application-org-lenderweb-app-iphone:kiva_oauth_callback?oauth_verifier=dk202zas&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app&state=6ED1279AB3340E9

Note the custom URL scheme in this redirect, *x-application-org-lenderweb-app-iphone*. Normally, the browser (Mobile Safari) would not know how to handle a URL redirect with this custom protocol but that Lender App pre-registered this custom protocol with iOS before directing the user to Kiva for authentication. It does this by making sure this scheme is listed as a valid URL Scheme in the *Info.plist* resource of the its application bundle. Additionally, the app implements a callback function (on its UIApplicationDelegate) to handle the incoming URL redirect from the browser:

h-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { // handle URL }

Lender App can then process the authentication code form the query string of the URL parameter to complete the authentication process as normal. (NOTE: In this case no the optional state parameter was not used since Lender App only supports operation by a single user.)

Out of Band

The Out of Band flow is simple means to authorize an application without relying on tight integration between your app and a the user's web browser. The user still must have access to Kiva via a web browser to complete the authorization but that browser may be on an entirely different device altogether. The application starts the process by directing the user to the OAuth authorization endpoint on Kiva along with its client ID. One option is for the application to open the URL in a local browser on the device, if available. Other options may include directing the user to visit a special website to start the process or sending the user an email or SMS with a link to begin the authorization process. Once the user is on Kiva, the user logs in and approves the app as normal, but rather than being programmatically redirected back to the application the user is presented with a short code that must be entered or pasted manually into the application. Because the authorization code must be transferred by the user outside of a consistent redirect flow we call this process "Out of Band." Despite the extra manual step of code entry, this flow may actually be easier or more intuitive for users who would otherwise be disoriented by URL redirects between different applications or websites.

For this flow we'll use the example of an application, Lender TV, designed to run on a smart TV without a dedicated web browser. Instead of directing the user to Kiva with a link or button, the app starts by instructing the user to visit a special website on a computer at home:

http://lenderweb.org/tv

TThis website is a simple page that informs the user the user will be redirected to Kiva in order to continue authorizing the Lender TV app to access their Kiva account. After a brief delay the user is redirected to the OAuth authorization endpoint using a special redirect URI, “oob”. The oauth_token is the request token you attained earlier:

https://www.kiva.org/oauth/authorize?client_id=org.lenderweb.app&response_type=code&oauth_callback=oob&state=6ED1279AB3340E9&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app

This reserved URI, called an URN, is reserved for applications wanting to use the Out of Band (OOB) flow. It lets Kiva know not to redirect the user back to the app via the browser, but to display a human-readable authorization code directly to the user after authorization. Thus, once our user logs in to Kiva and approves the app the user is shown a short sequence of characters like so:

R6KPLW

The user then has a fixed amount of time, about 30 minutes, to enter the code in the Lender TV app running on their television. She enters the code using their remote, clicks confirm, and Lender TV proceeds to validate the code entered via the Kiva API. If all goes well Lender TV will be returned an access token suitable for making API requests for their account history.

Embedded Browser

The final authorization flow supported by Kiva is very similar to the Browser Redirect flow except that the user handles login and approval via a browser view embedded directly in the application. This flow is acceptable for both native apps that want to avoid redirecting the user’s attention outside to an external browser, and web apps for which a traditional HTTP redirect or opening a separate browser window would result in an undesirable user experience. This flow is more complicated than others and also requires special care to prevent a secure and consistent authorization flow on the Kiva website.

To explain this flow we'll user Lender App again, but this time using a different redirect URI. Lender App starts the authentication process but popping up a floating browser view on the user's screen which is already set to the OAuth authorization endpoint:

https://www.kiva.org/oauth/authorize?client_id=org.lenderweb.app&response_type=code&oauth_callback=x-application-org-lenderweb-app-iphone%3Akiva_oauth_redirect&state=6ED1279AB3340E9&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app

At this point the user is presented with the Kiva login screen in the embedded browser view. She logs in and chooses to approve the application to access their private account data. Kiva performs an HTTP redirect as normal after the approval along with a new authorization code:

hx-application-org-lenderweb-app-iphone:kiva_oauth_callback?oauth_verifier=dk202zas&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app&state=6ED1279AB3340E9

Normally, the browser would automatically handle this redirect, but since Lender App has embedded this browser instance as an UIWebView it is also able to inspect and intercept any page load or redirects it sees fit using a UIWebViewDelegate. When it sees that the webview wants to load the special URL above it intercepts the request, processes the query string from the URL, detects and validates the authorization code with Kiva, then proceeds to close the embedded browser view and confirm the authorization process.

NOTE: For now embedded web views must use the same login and approval pages as for other flows. In the future we may provide options for optimizing the views for mobile devices and embedded web views.

Requesting Access

Regardless of the specific flow you choose for your application you need to redirect the user to the authorization page to start the authentication process:

https://www.kiva.org/oauth/authorize

Let's look a little deeper into starting the authentication request. There are two required parameters:

  • client_id - The client ID issued to your application by Kiva (see My Apps)
  • response_type - This value must be set to "code".
  • oauth_token - The request token previously obtained.
  • oauth_callback - The endpoint to which the authorization code will be returned. This must match the pre-registered value for your application. When using the Out Of Band flow this parameter must be set to “oob”.

There are also two optional parameters which we strongly recommend you use:

  • scope - A comma separated list of scopes that allow access to different potential resources. This will default to “access”, which will provide basic user information. Other scopes can be found in the API documentation.
  • state - This value is used by your application to correlate requests or otherwise track state across the authorization process. It can be set to any value and Kiva will maintain the value of this parameter for you in all request responses or redirects. If your application uses browser redirects in the authorization flow we strongly recommend you include a random session value in this parameter to prevent cross-site request forgeries.

All parameters are provided in the query string using the "application/x-www-form-urlencoded" format. Here's an example:

https://www.kiva.org/oauth/authorize?client_id=org.lenderweb&response_type=code&oauth_callback=https%3A%2F%2Flenderweb.org%2Fkiva_oauth_callback&state=6ED1279AB3340E9&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app

At this point the user will be prompted for login to Kiva (if necessary) and then given the option to grant the access to your application.

If the user approves this request the user will be redirected to the Redirect URI registered for your application along with the following parameters in the query string:

  • oauth_verifier - An authorization code valid for a short period of time which you can exchange for an access token.
  • oauth_token - The request token sent to the authorize page.
  • scope - A list of strings representing the scope of permissions granted by this authorization.
  • state - The same value of state which you originally provided to the application.

If the user does not approve your request or if there is an error with your request (invalid client_id, etc.) you will likely not receive a response. If possible, however, Kiva will return an error response to the Redirect URI with the following parameters:

  • error - A short string used to help determine the error. If the user explicitly denies access to your application this value will be "access_denied".
  • error_description - Optional. A human-readable string to help developer better understand the error.
  • state - The same value of state which you originally provided to the application.

REMEMBER: If you are using the Out Of Band flow there is no redirect. It is your application's responsibility to have the user enter the code in your application using the UI you provide.

Obtaining an Access Tokens

When your application is authorized by a user you are returned a short-lived one-time use credential or authorization code which you must subsequently exchange for an access token. This exchange is done using the oauth/access_token API:

POST https://api.kivaws.org/oauth/access_token
WARNING: Once again, if you are trying to sign your requests manually, don’t. Use a library: http://code.google.com/p/oauth/

This method must be called via HTTPS using the POST method with parameters passed in the HTTP request body. Note the oauth_verifier is the authorization code obtained from the user authorization flow.

If your request is successful the server will respond with a JSON object with the following properties:

  • oauth_token - The token identifier.
  • oauth_token_secret - The token key. This key should be protected securely as with all user private data.
  • scope - A list of strings representing the scope of permissions granted by this authorization.

Note that the access token is represented by three properties: oauth_token, oauth_token_secret and scope. You'll need to safely store all three of these values to make authenticated requests to the API.

If your request is rejected you will be returned a standard OAuth 1.0a error response. Your request may be rejected for any number of reasons including:

  • The authorization code expired. Authorization codes are short-lived and must be exchanged for tokens shortly after the authorization flow.
  • The authorization code has already been used. Authorization codes can only be exchanged once for an access token. The server may reject even if the first attempt to exchange the code was invalid.
  • Your client authentication does not match the client ID used in the corresponding authorization request.
  • Your Authorization header is incorrectly calculated, malformed, or corresponds to an invalid or restricted client.
  • Failure to use HTTPS for the request.
  • Missing or invalid parameters or any other errors in the construction of your POST request.

Remember, the access token issued to your application is sensitive information that should be kept private as it allows persistent access or modification of the user’s private data. Your application should never transmit the token key over insecure or unencrypted channels, and it should take appropriate measures to safeguard the token from theft and authorized use.

Kiva
  • © 2009 - 2017 Kiva. All rights reserved.
  • Terms Of Service
  • Kiva is a 501(c)(3) nonprofit.