cloudblog
2017/06/15
June 15, 2017
3 min read

Limit API Access with OAuth Scopes

OAuth scopes are a great way to segregate access to APIs and data. Combined with roles they can also be a powerful way to limit who gets access to what. Let's have a look at how you can implement scopes in WSO2 API Cloud.

Sample API

Let's start with a sample WorldBank API that has two resources: /countries and /indicators - both taking a code parameter: We have it published in Developer Portal and can invoke either of them with no problem (as long as we are subscribed to the API):

Adding Scopes

Now let's add two different scopes: one that would only give access to /countries and the other one that only gives access to /indicators. To do this:
  1. Open the API for editing,
  2. Go to the third step (Manage),
  3. Scroll down and click the Add Scopes button:
  4.  In the Define Scope dialog box, add the wb_geo scope for geographic data:
  5. Repeat the process to add wb_eco scope to the API.
  6. Now you can see both scopes available for the API. Click the + Scope button next to the /countries resource to assign its scope:
  7. Pick Geographic data for /countries and Economic data for /indicators:
  8. That's it: we defined two new scopes and applied them to two different REST resources. Now click Save and Publish to update the API:

Generate scope-limited OAuth token

Now if you open the API in Developer Portal's API Console, you will see two things: resources have notes about the scopes they need and attempts to invoke them with a regular OAuth key fail: To generate an OAuth token with the OAuth scope included:
  1. In Developer Portal (a.k.a. API Store), click Applications,
  2. In the application list, click the application which you used to subscribe to the API (for example, DefaultApplication),
  3. Click the Production Keys tab,
  4. Scroll down to the Scopes section, select the scopes you want (for example, Geographic data), and click the Re-generate button (I picked "-1" as the validity period to have a non-expiring token):
  5. Now if you go back to the API, you can use the new token and successfully invoke the API:

Adding Roles

If you want to limit scope access to particular groups of users, you follow the same procedure but this time also list the roles when adding your scopes. For example, in the screenshot below, I am limiting the wb_geo scope access to users in the researches role: