Secure an API with OAuth 2.0  |  Apigee  |  Google Cloud (2024)

This pageapplies to Apigee and Apigee hybrid.

View Apigee Edge documentation. Secure an API with OAuth 2.0 | Apigee | Google Cloud (1)

This tutorial shows how to secure an API proxy using an OAuth 2.0 access token.

Before you begin

To complete this tutorial, you must have access to an Apigee organization where youhave permission to:

  • Create and deploy API proxies
  • Create API products
  • Create developer apps

You must also have a properly configured environment group hostname with which you can make Apigee API proxy calls. If you are unsure about which environment group hostname to use, see your Apigee administrator.

Deploy the OAuth 2.0 proxy

We provide an API proxy on GitHub that is configured to generate OAuth 2.0 access tokens. Follow these steps to download and deploy this API proxy to your environment:

  1. Download the oauth sample API proxy to a directory on your file system.
  2. Go to the Apigee UI and sign in and select your Apigee organization.
  3. Select Develop > API Proxies in the left navigation bar.
  4. Click Create New.
    Secure an API with OAuth 2.0 | Apigee | Google Cloud (2)
  5. In the Create Proxy wizard, select Upload proxy bundle.
  6. Choose the oauth.zip file you downloaded, and click Next.
  7. Click Create.
  8. After the build completes, click the Edit proxy to view the new proxy in the API proxy editor.
  9. Click Deploy.
  10. Select the revision and environment to deploy to. You can leave the Service account field blank.
  11. Click Deploy.

You've successfully downloaded and deployed an access token-generating API proxy to your Apigee organization.

View the OAuth 2.0 flow and policy

Take a few moments to examine the OAuth 2.0 policy configuration.

New Proxy Editor

Next, you'll take a closer look at what the API proxy contains.

  1. In the API proxy editor, click the Develop tab.

    Secure an API with OAuth 2.0 | Apigee | Google Cloud (3)

    In the left-hand pane, you'll see two policies. You'll also see two POST flows in the Proxy Endpoints section.

  2. Click AccessTokenClientCredential under Proxy Endpoints. The text editor displays the XML code for the AccessTokenClientCredential conditional flow:
    <Flow name="AccessTokenClientCredential"> <Description/> <Request> <Step> <Name>GenerateAccessTokenClient</Name> </Step> </Request> <Response/> <Condition>(proxy.pathsuffix MatchesPath "/accesstoken") and (request.verb = "POST")</Condition></Flow>

    A flow is a processing step in an API proxy. In this case, the flow is triggered when a certain condition is met (it's called a "conditional flow"). The condition, defined in the <Condition> element, says that if the API proxy call is made to the /accesstoken resource, and the request verb is POST, then execute the GenerateAccessTokenClient policy, which generates the access token.

  3. Now let's look at the policy the conditional flow will trigger. Click the GenerateAccessTokenClient policy in the Request pane: Secure an API with OAuth 2.0 | Apigee | Google Cloud (4)

Classic Proxy Editor

Next, you'll take a closer look at what the API proxy contains.

  1. In the API proxy editor, click the Develop tab. In the left Navigator pane, you'll see two policies. You'll also see two POST flows in the Proxy Endpoints section.
  2. Click AccessTokenClientCredential under Proxy Endpoints.
    Secure an API with OAuth 2.0 | Apigee | Google Cloud (5)

    In the XML code view, you'll see a Flow called AccessTokenClientCredential:

    <Flow name="AccessTokenClientCredential"> <Description/> <Request> <Step> <Name>GenerateAccessTokenClient</Name> </Step> </Request> <Response/> <Condition>(proxy.pathsuffix MatchesPath "/accesstoken") and (request.verb = "POST")</Condition></Flow>

    A flow is a processing step in an API proxy. In this case, the flow is triggered when a certain condition is met. The condition, defined in the <Condition> element, is that if the API proxy call is made to the /accesstoken resource, and the request verb is POST, then execute the GenerateAccessTokenClient policy, which generates the access token.

  3. Now let's look at the policy the conditional flow will trigger. Click the GenerateAccessTokenClient policy icon in the flow diagram.

    Secure an API with OAuth 2.0 | Apigee | Google Cloud (6)

The following XML configuration is displayed:

<OAuthV2 name="GenerateAccessTokenClient"> <!-- This policy generates an OAuth 2.0 access token using the client_credentials grant type --> <Operation>GenerateAccessToken</Operation> <!-- This is in milliseconds, so expire in an hour --> <ExpiresIn>3600000</ExpiresIn> <SupportedGrantTypes> <!-- This part is very important: most real OAuth 2.0 apps will want to use other grant types. In this case it is important to NOT include the "client_credentials" type because it allows a client to get access to a token with no user authentication --> <GrantType>client_credentials</GrantType> </SupportedGrantTypes> <GrantType>request.queryparam.grant_type</GrantType> <GenerateResponse/></OAuthV2>

The configuration includes the following:

  • The <Operation>, which can be one of several predefined values, defines what the policy is going to do. In this case, it's going to generate an access token.
  • The token will expire 1 hour (3600000 milliseconds) after being generated.
  • In <SupportedGrantTypes>, the OAuth 2.0 <GrantType> expected to be used is client_credentials (exchanging a consumer key and secret for an OAuth 2.0 token).
  • The second <GrantType> element tells the policy where to look in the API call for the grant type parameter, as required by the OAuth 2.0 specification. (You'll see this in the API call later). The grant type could also be sent in the HTTP header (request.header.grant_type) or as a form parameter (request.formparam.grant_type).

You don't need to do anything else with the API proxy at the moment. In later steps, you'll use this API proxy to generate an OAuth 2.0 access token. But first, you need to do a few more things:

  • Create the API proxy you actually want to secure with OAuth 2.0.
  • Create a few more artifacts that will result in the consumer key and consumer secret you need to exchange for an access token.

Create a protected API proxy

Now you're going to create the API proxy you want to protect. This is the API call that returns something you want. In this case, the API proxy will call Apigee's mocktarget service to return your IP address. BUT, you'll get to see it only if you pass a valid OAuth 2.0 access token with your API call.

The API proxy you create here will include a policy that checks for an OAuth 2.0 token in the request.

  1. Select Develop > API Proxies in the left navigation bar.
  2. Click Create New.
    Secure an API with OAuth 2.0 | Apigee | Google Cloud (7)
  3. In the Build a Proxy wizard, select Reverse proxy (most common).
  4. Configure the proxy with the following:
    In this field do this
    Proxy Name Enter: helloworld_oauth2
    Project Base Path

    Change to: /hellooauth2

    The Project Base Path is part of the URL used to make requests to the API proxy.

    Existing API

    Enter: https://mocktarget.apigee.net/ip

    This defines the target URL that Apigee invokes on a request to the API proxy.

    Description Enter: hello world protected by OAuth 2.0
  5. Click Next.
  6. On the Common policies page:
    In this field do this
    Security: Authorization Select:
    • OAuth 2.0

    These options are very handy. They'll automatically add two policies to your API proxy and create an API product.

  7. Click Next.
  8. On the Summary page, under Optional Deployment, select an environment, and click Create and Deploy.
  9. Click Edit proxy to display the Overview page for the API proxy.
    The API proxy is automatically deployed for you. (It may take a few moments for the deployment to complete.)

View the policies

Let's take a closer look at what you've created.

New Proxy Editor

  1. In the API proxy editor, click the Develop tab. You'll see that two policies have been added to the request flow of the API proxy:
    • Verify OAuth v2.0 Access Token – Checks the API call to make sure a valid OAuth 2.0 token is present.
    • Remove Header Authorization – An Assign Message policy that removes the access token after it's checked, so that it doesn't get passed to the target service. (If the target service needed the OAuth 2.0 access token, you wouldn't use this policy).
  2. Click the Verify OAuth v2.0 Access Token icon in the right-hand pane and look at the XML below it in the text editor.

Classic Proxy Editor

  1. In the API proxy editor, click the Develop tab. You'll see that two policies have been added to the request flow of the API proxy:
    • Verify OAuth v2.0 Access Token – Checks the API call to make sure a valid OAuth 2.0 token is present.
    • Remove Header Authorization – An Assign Message policy that removes the access token after it's checked, so that it doesn't get passed to the target service. (If the target service needed the OAuth 2.0 access token, you wouldn't use this policy).
  2. Click the Verify OAuth v2.0 Access Token icon in the flow view and look at the XML below it in the code pane.

    Secure an API with OAuth 2.0 | Apigee | Google Cloud (8)

<OAuthV2 async="false" continueOnError="false" enabled="true" name="verify-oauth-v2-access-token"> <DisplayName>Verify OAuth v2.0 Access Token</DisplayName> <Operation>VerifyAccessToken</Operation></OAuthV2>

Notice that the <Operation> is VerifyAccessToken. The Operation defines what the policy is supposed to do. In this case, it's going to check for a valid OAuth 2.0 token in the request.

Add an API product

To obtain an OAuth 2.0 access token, you need to create three Apigee entities: an API product, a developer, and a developer app. First, create the API product:

  1. Select Publish > API Products.
  2. Click +Create.
  3. Enter the Product Details for your API product.
    FieldDescription
    NameInternal name of the API product. Do not specify special characters in the name.
    Note: You cannot edit the name once the API product is created.
    Display nameDisplay name for the API product. The display name is used in the UI and you can edit it at any time. If not specified, the Name value will be used. This field is auto-filled using the Name value; you can edit or delete its contents. The display name can include special characters.
    DescriptionDescription of the API product.
    Environment Environments to which the API product will allow access. Select the environment to which you deployed the API proxy.
    AccessSelect Public.
    Automatically approve access requestsEnable automatic approval of key requests for this API product from any app.
    QuotaIgnore for this tutorial.
    Allowed OAuth 2.0 ScopesIgnore for this tutorial.
  4. In the Operations section, click Add An Operation.
  5. In the API Proxy field, select the API proxy you just created.
  6. In the Path field, enter "/". Ignore the other fields.
  7. Click Save to save the Operation.
  8. Click Save to save the API product.

Add a developer and app to your organization

Next, you're going to simulate the workflow of a developer signing up to use your APIs. Ideally, developers register themselves and their apps through your developer portal. In this step, though, you'll add a developer and an app as an administrator.

A developer will have one or more apps that call your APIs, and each app gets a unique consumer key and consumer secret. This key/secret-per-app also gives you, the API provider, more granular control over access to your APIs and more granular analytics reporting on API traffic, because Apigee knows which developer and app belong to which OAuth 2.0 token.

Create a developer

Let's create a developer named Nigel Tufnel.

  1. Select Publish > Developers in the menu.
  2. Click + Developer.
  3. Enter the following in the New Developer window:
    In this field Enter
    First Name Nigel
    Last Name Tufnel
    Username nigel
    Email nigel@example.com
  4. Click Save.

Register an app

Let's create an app for Nigel.

  1. Select Publish > Apps.
  2. Click + App.
  3. Enter the following in the New App window:
    In this field do this
    Name and Display Name Enter: nigel_app
    Developer Click Developer and select: Nigel Tufnel (nigel@example.com)
    Callback URL and Notes Leave blank
  4. Under Products, click Add product.
  5. Add the API product you just created.
  6. Click Create.

Get the consumer key and consumer secret

Now you'll get the consumer key and consumer secret that will be exchanged for an OAuth 2.0 access token.

  1. Ensure that the nigel_app page is displayed. If not, on the Apps page (Publish > Apps), click nigel_app.
  2. On the nigel_app page, click Show in the Key and Secret columns. Notice that the key/secret are associated with the API product that you created earlier.

  3. Select and copy the Key and Secret. Paste them in a temporary text file. You'll use them in a later step, where you call the API proxy that will exchange these credentials for an OAuth 2.0 access token.

Try calling the API to get your IP address (fail!)

Try calling the protected API proxy that you just created. Notice that you are not passing an OAuth 2.0 access token in the call.

where YOUR ENV_GROUP_HOSTNAME is the environment group hostname. See Find the environment group hostname.

Because the API proxy has the Verify OAuth v2.0 Access Token policy checking for a valid OAuth 2.0 token in the request, the call should fail with the following message:

{"fault":{"faultstring":"Invalid access token","detail":{"errorcode":"oauth.v2.InvalidAccessToken"}}}

In this case, failure is good! It means your API proxy is much more secure. Only trusted apps with a valid OAuth 2.0 access token can successfully call this API.

Get an OAuth 2.0 access token

Next, you will use the key and secret you copied and pasted into a text file and exchange them for an OAuth 2.0 access token. You're now going to make an API call to the API sample proxy you imported, oauth, which will generate an API access token.

Using that key and secret, make the following cURL call (note that the protocol is https):

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" \"https://YOUR ENV_GROUP_HOSTNAME/oauth/client_credential/accesstoken?grant_type=client_credentials" \-d "client_id=CLIENT_KEY&client_secret=CLIENT_SECRET"

Note that if you're using a client like Postman to make the call, the client_id and client_secret go in the Body of the request and must be x-www-form-urlencoded.

You should get a response like this:

{ "issued_at" : "1466025769306", "application_name" : "716bbe61-f14a-4d85-9b56-a62ff8e0d347", "scope" : "", "status" : "approved", "api_product_list" : "[helloworld_oauth2-Product]", "expires_in" : "3599", //--in seconds "developer.email" : "nigel@example.com", "token_type" : "BearerToken", "client_id" : "xNnREu1DNGfiwzQZ5HUN8IAUwZSW1GZW", "access_token" : "GTPY9VUHCqKVMRB0cHxnmAp0RXc0", "organization_name" : "myOrg", "refresh_token_expires_in" : "0", //--in seconds "refresh_count" : "0"}

You got your OAuth 2.0 access token! Copy the access_token value (without the quote marks) and paste it into your text file. You'll use it in a moment.

What just happened?

Remember previously when you looked at that "conditional flow" in the oauth proxy, the one that said if the resource URI is /accesstoken and the request verb is POST, to execute the GenerateAccessTokenClient OAuth 2.0 policy that generates an access token? Your cURL command met those conditions, so the OAuth 2.0 policy was executed. It verified your consumer key and consumer secret and exchanged them for an OAuth 2.0 token that expires in 1 hour.

Call the API with an access token (success!)

Now that you have an access token, you can use it to call the API proxy. Make the following cURL call. Substitute your Apigee organization name and the access token.

curl https://YOUR ENV_GROUP_HOSTNAME/hellooauth2 -H "Authorization: Bearer TOKEN"

You should now get a successful call to the API proxy that returns your IP address. For example:

{"ip":"::ffff:192.168.14.136"}

You can repeat that API call for close to an hour, after which time the access token will expire. To make the call after an hour, you'll need to generate a new access token using the previous steps.

Congratulations! You've created an API proxy and protected it by requiring that a valid OAuth 2.0 access token be included in the call.

  • OAuth 2.0 home
  • OAuthV2 policy
  • Download API proxies (which shows how to bundle an API proxy into a ZIP file like the one you downloaded)
Secure an API with OAuth 2.0  |  Apigee  |  Google Cloud (2024)

FAQs

Why is a bad idea to use OAuth 2.0 for authentication? ›

Leaking authorization codes and access tokens. Perhaps the most infamous OAuth-based vulnerability is when the configuration of the OAuth service itself enables attackers to steal authorization codes or access tokens associated with other users' accounts.

How to use OAuth 2.0 in API? ›

Basic steps
  1. Obtain OAuth 2.0 credentials from the Google API Console. ...
  2. Obtain an access token from the Google Authorization Server. ...
  3. Examine scopes of access granted by the user. ...
  4. Send the access token to an API. ...
  5. Refresh the access token, if necessary.

What is the OAuth 2.0 policy for keeping apps secure? ›

OAuth 2.0 clients for web apps must secure their data using HTTPS redirect URIs and JavaScript origins, not plain HTTP. Google can reject OAuth requests that don't originate from or resolve to a secure context.

How to secure an API without authentication? ›

API Without Authentication: Risks and Solutions
  1. Implement Strong Authentication Methods.
  2. Enforce Role-Based Access Controls (RBAC)
  3. Implement Multi-Factor Authentication (MFA)
  4. Encrypt Sensitive Data.
  5. Monitor and Log API Activities.
  6. Regularly Update and Patch APIs.
Jan 3, 2024

Should I use OAuth for my API? ›

REST API security is important to prevent unauthorized access to data. There are two main ways to secure REST APIs: API keys and OAuth tokens. API keys are good for read-only data, but not as good for authorization. OAuth tokens are better for authorization, but can be more complex to implement.

What is the most secure way of authenticating an API? ›

HTTP Bearer Authentication: API consumers send API requests with a unique API access token in an HTTP header. API providers then validate the API access token to authenticate API users. This API authentication method is more secure than Basic, as API requests cannot be intercepted easily.

What is OAuth 2.0 in simple terms? ›

OAuth 2.0, which stands for “Open Authorization”, is a standard designed to allow a website or application to access resources hosted by other web apps on behalf of a user.

Why is OAuth more secure? ›

Why Apidog for OAuth Integration. Enhanced Security: OAuth does not require users to provide their credentials directly to third parties, significantly reducing the risk of credential exposure.

Why is OAuth better than basic authentication? ›

OAuth operates on a sophisticated mechanism that involves several steps to ensure secure access to the user data: Authorization by the User: A user approves a third-party application's request to access their data hosted by a service provider.

What is the difference between oauth2 and app password? ›

Oauth provides an extra layer of security for your email address so that the password to your email is not exposed to applications. In lieu, the generated app password is what will be entered in the password field for services like TDO Letters Module.

What are the advantages of OAuth 2.0 authentication? ›

The Benefits Of OAuth Authentication
  • Increased Security. ...
  • Improved User Experience. ...
  • Reduced Development Time And Costs. ...
  • Flexibility And Compatibility. ...
  • Reduced Fraud And Identity Theft. ...
  • Increased Access Control. ...
  • Seamless Integration With Third-Party Applications. ...
  • Easy Revocation Of Access.

Is Basic Auth for API secure? ›

Cons of basic authentication

While this method is easy to implement, it's not very secure. The username and password are encoded with Base64, but they aren't encrypted and can easily be decoded by a third party. Once decoded, the third party has a valid username and password that can be used to access your API.

How does OAuth 2.0 work in the rest API? ›

OAuth 2.0 is a standard for implementing delegated authorization, and authorization is based on the access token required to access a resource. The access token can be issued for a given scope, which defines what the access token can do and what resources it can access.

How can I secure my API? ›

API Security Best Practices
  1. Always Use a Gateway.
  2. Always Use a Central OAuth Server.
  3. Only Use JSON Web Tokens Internally.
  4. Use Scopes for Coarse-Grained Access Control.
  5. Use Claims for Fine-Grained Access Control at the API Level.
  6. Trust No One.
  7. Create or Reuse Libraries for JWT Validation.
  8. Do Not Mix Authentication Methods.

How do I know if my API is secure? ›

Steps to Follow for API Security Testing
  1. Define API Endpoints:
  2. Identify Sensitive Endpoints and Vulnerabilities:
  3. Map API Endpoints:
  4. Evaluate Authentication Effectiveness:
  5. Examine Authorization Controls:
  6. Test for Improper Access Controls:
  7. Analyze Input Validation Techniques:
  8. Ensure Data Integrity:
Jul 4, 2023

Why is OAuth2 not authentication? ›

Authentication is ignored in OAuth2 and OIDC because it is a separate concern. This allows OAuth2 and OIDC to focus on the nitty gritty details of getting the resource owner to the authorization server as well as generating access and identity tokens.

Can OAuth 2.0 be used for authentication? ›

OAuth 2.0 is an authorization protocol and NOT an authentication protocol. As such, it is designed primarily as a means of granting access to a set of resources, for example, remote APIs or user data.

Is OAuth2 outdated? ›

It states that OAuth 2.0 is deprecated.

Why do you probably not need OAuth2 OpenID Connect? ›

OAuth2 is not an authentication (login) protocol!

The purpose of OAuth2 Tokens is to authorize requests at a first party server (or API). If the third party uses the OAuth2 Access Token as proof of authentication, an attacker could easily impersonate a legitimate user.

Top Articles
Latest Posts
Article information

Author: Lakeisha Bayer VM

Last Updated:

Views: 5543

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Lakeisha Bayer VM

Birthday: 1997-10-17

Address: Suite 835 34136 Adrian Mountains, Floydton, UT 81036

Phone: +3571527672278

Job: Manufacturing Agent

Hobby: Skimboarding, Photography, Roller skating, Knife making, Paintball, Embroidery, Gunsmithing

Introduction: My name is Lakeisha Bayer VM, I am a brainy, kind, enchanting, healthy, lovely, clean, witty person who loves writing and wants to share my knowledge and understanding with you.