Management API
Management API
Contents
Introduction to Azure API Management .................................................................................... 3
Learning objectives .................................................................................................................................................... 3
Introduction .................................................................................................................................................................. 3
Example scenario ........................................................................................................................................................ 5
What will we be doing? ............................................................................................................................................ 6
What is the main goal?............................................................................................................................................. 6
What is Azure API Management? ......................................................................................................................... 6
What is API lifecycle management? .................................................................................................................... 7
Azure API Management definition....................................................................................................................... 7
Gateway.......................................................................................................................................................................... 8
Administration interface .......................................................................................................................................... 9
Developer portal ......................................................................................................................................................... 9
Azure API Management tiers ................................................................................................................................. 9
Apply policies to API requests and responses.............................................................................................. 10
How Azure API Management works................................................................................................................. 11
How Azure API Management works for API consumers .......................................................................... 12
How Azure API Management works for API providers ............................................................................. 13
How Azure API Management works for app developers ......................................................................... 15
When to use Azure API Management ............................................................................................................. 16
Decision criteria ................................................................................................................................................... 16
Apply the criteria ................................................................................................................................................. 17
Should you use Azure API Management to standardize APIs? ......................................................... 17
Should you use Azure API Management to centralize API operations? ........................................ 18
Should you use Azure API Management to secure access to your APIs? ..................................... 19
Control authentication for your APIs with Azure API Management ..................................... 20
Introduction ............................................................................................................................................................... 20
1
Sandip Bhole
Enterprise Cloud Solution Architect
2
Sandip Bhole
Enterprise Cloud Solution Architect
Summary ...................................................................................................................................... 39
Learning objectives
By the end of this document, you'll be able to:
• Evaluate whether Azure API Management is appropriate for managing and exposing
your organization's APIs.
• Determine how API Management works for API consumers, API providers, and app
developers to provide secure and controlled exposure of APIs.
Introduction
• Onboarding users
• Managing revisions
• Implementing security
• Running analytics
Now imagine that like many of today's leading companies, your organization publishes
multiple APIs for different types of users including partners, developers, and employees.
These APIs are used in multiple settings, including mobile and web apps, and Internet of
Things (IoT) devices.
3
Sandip Bhole
Enterprise Cloud Solution Architect
How do you reduce the complexity inherent in having numerous APIs? Microsoft Azure
API Management acts as a "front door" for all your APIs. Azure API Management manages
all your API traffic and offers intuitive portals for managing your APIs and surfacing them
to developers. It also provides tools for implementing security, managing revisions, and
performing analytics.
4
Sandip Bhole
Enterprise Cloud Solution Architect
Example scenario
Suppose you work at a company that operates a food-delivery platform. Your customers
use your mobile app or website to browse the menus of multiple restaurants. They then
place an order for the food they want, which your company delivers. The backbone of
your platform is a large collection of APIs. For example, the APIs that you publish are used
by:
5
Sandip Bhole
Enterprise Cloud Solution Architect
Each published API resides on a different server, has its own process for onboarding users,
and has its own policies for security, revisions, analytics, and more. You've been tasked to
find a way to reduce this complexity. Here you learn how Azure API Management can
standardize, centralize, and help secure all the aspects of publishing and maintaining APIs
across the full API lifecycle.
Examining Azure API Management to help you decide if it's the correct solution to reduce
your company's API complexity, by studying these three main components:
• Gateway. A single endpoint for all your API calls, which eases the implementation
of security, rate limits, caching, and transformations.
• Administration interface. A single interface where you import APIs, set policies,
create API products, manage users and groups, and run analytics.
• Developer portal. A website that brings all your APIs into a single location for
developers to read documentation, test APIs, review code samples, get API keys, and
run analytics.
We'll also study Azure API Management from these three user angles:
• API consumers. Entities (such as applications) that get value from using an API.
• API providers. People who administer and maintain APIs.
• App developers. People who build applications that consume APIs.
By the end of this session, you can evaluate whether Azure API Management is the correct
solution for keeping your organization's APIs under a single management umbrella.
Let's start with a quick overview of Azure API Management and its core features. This
overview should help you decide whether Azure API Management might be a suitable
solution for reducing your company's API complexity.
6
Sandip Bhole
Enterprise Cloud Solution Architect
API lifecycle management is the process of administering an API through its entire
lifespan—from its design and creation to its obsolescence and retirement. For the
purposes of this document, we'll pick up after your APIs have already been designed,
coded, and deployed. Let's concentrate on the rest of the API lifecycle management tasks,
which include:
Azure API Management is a cloud service that gives you a platform for publishing,
securing, maintaining, and analyzing all your company's APIs. Azure API Management
accomplishes these tasks by offering three main components:
• Gateway
• Administration interface
• Developer portal
7
Sandip Bhole
Enterprise Cloud Solution Architect
Important
Azure API Management does not host your actual APIs; your APIs remain where they were
originally deployed. Instead, Azure API Management acts as a kind of façade or "front
door" for your APIs. In this way, Azure API Management decouples your APIs by letting
you set API policies and other management options in Azure, while leaving your deployed
backend APIs untouched.
Gateway
The Azure API Management gateway is an Azure endpoint that accepts all calls from all
your APIs. The gateway:
8
Sandip Bhole
Enterprise Cloud Solution Architect
Administration interface
The Azure API Management administration interface is a set of Azure portal pages and
tools that enable you to administer your service and your APIs. In addition to provisioning,
scaling, and monitoring the service, you use the administrative interface for:
The Azure API Management developer portal is a fully customizable website that enables
developers to interact with your APIs through:
Azure API Management provides several service tiers, each offering a distinct set of
features, capacities, and pricing. The following table lists the tiers in order from lowest to
highest price and compares some key capabilities.
9
Sandip Bhole
Enterprise Cloud Solution Architect
Note
The pricing for the Consumption tier is per API call, where the first million calls are free,
and the remainder are then billed at a fixed rate per 10,000 calls. Pricing for all the other
tiers is per hour.
One of the biggest problems with having multiple published APIs is that each API requires
a separate set of policies. Here, a policy is a setting or action that controls the behavior of
the API. For example, if you want to enforce a rate limit (the maximum number of API calls
allowed from a single source in a given time period) you'd include that limit as part of the
policies for an API. A rate limit is just one example, but there are numerous policies you
can apply. Multiply that by several different APIs and you have a management nightmare.
Azure API Management solves the API policy problem by enabling you to set policies for
all your APIs in a single place, which is the Azure API Management administration
interface. With Azure API Management, you can set policies in many categories. A partial
list includes:
• Access restriction. These policies determine when an API request is allowed through
the gateway. For example, enforce rate limits and usage quotas, filter caller IPs, and
check for a valid JSON Web Token (JWT).
• Authentication. Authenticate API calls, for example, by using Basic authentication,
a client certificate, or a managed identity.
• Caching. Improve API performance by storing and retrieving responses in the cache.
• Validation. Validate API calls by comparing certain parameters to what's in your API
specification. For example, validate the request or response body, the request header
parameters, and the response headers.
10
Sandip Bhole
Enterprise Cloud Solution Architect
Flexibly combine your policies in policy definitions, which are XML documents that consist
of a series of statements, each of which represents a policy and its parameters. Policy
definitions let you configure separate policies at different stages of the API request-
response pipeline:
Here, we discuss how Azure API Management works from three points of use. This
knowledge helps you continue to evaluate whether Azure API Management is a good
solution for managing your organization's APIs.
In this unit, you learn about how Azure API Management works for the following types of
users:
• API consumers
• API providers
• App developers
11
Sandip Bhole
Enterprise Cloud Solution Architect
An API consumer is an entity that makes a request to the API for data. For example, any
of these entities could be an API consumer:
• Mobile app
• Web app
• IoT device
The key Azure API Management component for consumers is the gateway. All consumer
API calls are first routed to your gateway endpoint. API consumers only ever interact
directly with the gateway, and never with the actual API deployment instance.
The gateway performs many tasks from the consumer's point of view, but the following
are the most important:
• Authentication. The gateway monitors access to the API by verifying the consumer's
subscription keys, JWT tokens, and other credentials.
• Security. The gateway prevents API misuse by enforcing predefined rate limits and
consumer usage quotas, or by validating requests and responses against the API's
schema.
• Transformation. The gateway transforms the API request or response as needed.
For example, if the backend service responds with XML data, you can modernize the
API by transforming the XML into JSON automatically, as depicted in the following
image.
• Routing. After an API request is authenticated, validated, and transformed, the
gateway routes the call to the backend service where the API is deployed.
• Performance. The gateway can store the backend API response in a cache. In
situations where the backend response is static over time, serving subsequent
responses from the cache gives consumers faster response times and reduces the
load on the backend server.
12
Sandip Bhole
Enterprise Cloud Solution Architect
If you're an API provider, you still have a great deal of work to do after your APIs have
been published. This work includes:
You can perform all these tasks and more, by using the Azure API Management
administration interface in the Azure portal. Or, by using tools such as Azure CLI or Azure
PowerShell. Besides enabling you to set API policies (as you learned in the previous unit),
the administration interface enables you to perform the following tasks:
• Define and import API specs. Import an OpenAPI specification, a REST API, a
Simple Object Access Protocol (SOAP) API (which you can optionally convert to
13
Sandip Bhole
Enterprise Cloud Solution Architect
REST), a WebSocket API, or a GraphQL API. You can also create an API by importing
instances of the following Azure services: Web App, Container App, Function App,
Logic App, and Service Fabric. You can also create a blank API and define it manually.
• Manage users and groups.
o A user is a developer account. It's an account for an API consumer. You
can add users manually or invite users to create an account, but most
users create their own accounts by using the developer portal.
o A group is a collection of related users. You can associate a group with a
particular API product, and then each user in that group has access to the
product in the developer portal.
• Package APIs into products. In Azure API Management, a product is a group of
related APIs. By packaging multiple APIs as a single product, you can configure just
the product instead of configuring all the APIs separately. For example, set rate limits
and other policies, define terms of use, add groups, and so on. This configuration
gets applied to all the APIs in the product. After you publish the product, consumers
can subscribe to it and use its APIs with a single subscription key.
• Manage API revisions and versions. When your API developer team needs to make
changes to an API, expose the change in a safe and controlled manner that doesn't
adversely affect consumers by using revisions and versions:
o A revision is a relatively minor or nonbreaking change to an API. Your
development team can code and test the revision separately from the
production API, as in the following image. Then, when your revision is
ready for consumers, use the Azure API Management administration
interface to set the updated API as the current revision.
o A version is a relatively major or breaking change to an API. Azure API
Management enables you to offer developers multiple versions of the API
simultaneously. It also offers several versioning schemes, including path-
based, header-based, and query string-based versioning.
• Monitor and analyze APIs. The administration interface includes built-in
monitoring tools to trace and review API traffic in real time, and analytics for insights
on how consumers are using your published APIs. Azure API Management also
supports several Azure tools for monitoring APIs and running analytics workloads.
Azure services supported by Azure API Management include Azure Monitor Logs,
Application Insights, and Event Hubs.
14
Sandip Bhole
Enterprise Cloud Solution Architect
Except for the Consumption tier, all Azure API Management instances include a developer
portal where you surface your APIs to potential and existing API consumers. The developer
portal comes with a default interface that's customizable to match your organization's
branding and requirements.
App developers with developer accounts sign in to the developer portal (which also
accepts guest users who don't yet have an account). Developers are then presented with
a web interface that enables them to interact with APIs in the following ways:
15
Sandip Bhole
Enterprise Cloud Solution Architect
Now let's discuss some scenarios that illustrate when it's appropriate to use Azure API
Management. Using the food delivery service as an example, let's investigate API lifecycle
management with respect to standardizing APIs, centralizing API management and
exposure, and enhancing API security. We can use the following criteria to help you decide
whether Azure API Management is a suitable choice for managing and publishing your
organization's inventory of APIs:
Decision criteria
Criteria Analysis
Number of APIs The key consideration is the number of APIs that you manage.
The more APIs you've deployed, the greater the need for
deployment standardization and centralization of API control.
Rate of API changes The next consideration is the rate at which your organization
implements API revisions and versions. The faster you create API
revisions and publish new API versions, the greater the need for
a robust and flexible versioning control system.
API administration The last consideration is how much policy overhead you apply to
load your APIs. Policies such as usage quotas, call rate limits, request
transformations, and request validation. The more configurations
and options your APIs require, the greater the need for
standardized and centralized policy implementations.
16
Sandip Bhole
Enterprise Cloud Solution Architect
Azure API Management is the correct choice for managing APIs through their lifecycles
when you have a large API deployment that changes frequently and requires significant
policy overhead. However, these criteria don't apply equally to all use cases. Let's consider
how these criteria apply to the use cases for our scenario.
• Specifications. Standardizing API specs—such as using REST for all APIs and using
a consistent naming scheme for JSON name-value pairs—reduces development
time, decreases errors, and enables your organization to respond faster to customer
suggestions and market forces.
• Documentation. Standardizing API documentation enables developers to get up to
speed with an API quickly. It also reduces technical support queries and encourages
developers to use more of your APIs.
• URLs. Standardizing the base URL for your APIs reduces consumer errors and gives
your API deployments a more professional appearance.
• Analytics. Standardizing API analytics enables management teams and engineers to
compare usage and performance across multiple APIs.
• Regulations. For APIs that must meet government or industry rules and regulations,
standardization helps ensure compliance across all APIs.
17
Sandip Bhole
Enterprise Cloud Solution Architect
This need is true of the food delivery platform scenario, which requires consistency across
the APIs for the mobile app, the web app, and the partner restaurants.
Azure API Management enhances the centralization of all API operations by bringing
multiple APIs under a single administrative umbrella. Without an API management service,
each API is on its own in terms of administration, deployment, and developer access. This
decentralized model often results in duplicated efforts and increased overhead.
Centralizing API operations can result in the following benefits:
18
Sandip Bhole
Enterprise Cloud Solution Architect
The efficiencies that accrue from centralizing API operations tend to increase with the
number of APIs and with the overall administrative load size you impose on your APIs.
Having centralized APIs is a huge help when APIs are frequently updated because it
enables a single versioning scheme for all products.
All these factors apply strongly to our food delivery platform scenario. For example,
centralized consumer access through the developer portal makes it easier to sign up new
developers, enhancing the monetization of the platform's APIs.
Should you use Azure API Management to secure access to your APIs?
Azure API Management was designed with API security in mind. So many organizations
rely on APIs for the internal and external exchange of data between apps and devices. A
haphazard or inconsistent approach to security is just asking for trouble. A proper API
security strategy covers the following bases:
• Permissions. Control who can work with an API and what they can do with it. In
Azure API Management, having all your API consumers as users and being able to
organize those users into groups makes it easier and more efficient to apply
permissions to control API access.
• Access. Only allow authorized users to submit requests. With Azure API
Management, the developer portal supplies users with subscription keys, and you
can restrict access to APIs by using multiple forms of authentication and JSON web
tokens.
• Protection. Secure the API from malicious usage. Azure API Management enables
you to throttle API access by using rate limits and usage quotas to help prevent
consumer misuse (intentional or accidental) of the API.
• Compliance. Make sure your APIs satisfy all corporate or government security
policies. Having all your APIs together in Azure API Management makes it easier to
configure those APIs with security policies that achieve compliance.
The more APIs you manage, the greater the need for security. Having more APIs, means
a greater attack surface and a greater risk of accidental data breaches or leaks. Also, the
19
Sandip Bhole
Enterprise Cloud Solution Architect
more often you revise your APIs, the greater the chance that a revision or new version can
uncover a security flaw.
These security concerns are paramount in our food delivery scenario. Our platform
generates and stores a great deal of sensitive data, including restaurant payments,
customer names and addresses, and delivery vehicle locations.
Introduction
Azure API Management enables you to carefully identify and control who can access the
data published by your APIs.
Suppose you work for a meteorological company, which has an API that customers use
to access weather data for forecasts and research. There's proprietary information in this
data, and you would like to ensure that only paying customers have access. You want to
use Azure API Management to properly secure this API from unauthorized use.
In this module, you'll use two different methods to secure access to an API in Azure API
Management:
• Subscriptions
• Client Certificates
By the end of this module, you'll be able to ensure that only people with the right
credentials can access the information in your API.
Learning objectives
20
Sandip Bhole
Enterprise Cloud Solution Architect
Azure API Management (APIM) helps organizations unlock the potential of their data and
services by publishing APIs to external partners, and internal developers. Businesses are
extending their operations as a digital platform by creating new channels, finding new
customers, and driving deeper engagement with existing ones. APIM provides the core
competencies to ensure a successful API program through developer engagement,
business insights, analytics, security, and protection. You can use APIM to take any
backend and launch a full-fledged API program based on it.
To use APIM, administrators define APIs in the portal. Each API consists of one or more
operations, and can be added to one or more products. To use an API, developers
subscribe to a product that contains that API, and then call the API's operation, subject to
any usage policies that might be in effect. Common scenarios include:
• Securing mobile infrastructure by gating access with API keys, preventing
denial of service attacks (DoS) by using throttling, or using advanced security
policies like JSON Web Token (JWT) validation.
• Offering fast partner onboarding through the developer portal to
independent software vendor (ISV) partner ecosystems. Enabling them to
build an API facade to decouple from internal implementations that aren't
ready for partner consumption.
• Running an internal API program that offers a centralized location for the
organization to communicate between the API gateway and the backend.
Communications about the availability and latest changes to APIs would be
on a secured channel with gated access based on organizational accounts.
API gateway
21
Sandip Bhole
Enterprise Cloud Solution Architect
Azure portal
The Azure portal is the administrative interface where you set up your API program. You
can also use it to:
Developer portal
The Developer portal serves as the main web presence for developers. From here they
can:
When you publish an API with APIM, you define who can access the API through the
gateway.
For your meteorological app, you want to ensure that only customers who have
subscribed to your service can access the API and use your forecast data. You accomplish
this access control by issuing subscription keys.
Important
22
Sandip Bhole
Enterprise Cloud Solution Architect
Subscriptions in this context are not related to Azure subscriptions used for managing
your Azure account.
Here, you'll learn how to use subscription keys to secure your APIs.
You can choose to publish your APIs and the information they contain for free. But usually,
you want to restrict access to users who have paid or organizations with which you have
a working relationship. You can control access to your APIs by using subscriptions.
Subscriptions are used to segment the access levels to an API.
Subscription keys form the authorization to enable access to these subscriptions.
Whenever a client makes a request to a protected API, a valid subscription key must be
included in the HTTP request, otherwise the call will be rejected.
A subscription key is a unique auto-generated key that can be passed as part of an API
call. The key is directly related to a subscription, which can be scoped to different areas.
Subscriptions give you granular control over permissions and policies.
The three main subscription scopes are:
Scope Details
All APIs Applies to every API accessible from the gateway.
Single API Applies to a single imported API and all of its endpoints.
Product A product is a collection of one or more APIs that you configure in APIM. You can assign APIs
to more than one product. Products can have different access rules, usage quotas, and
terms of use. So, if you want your partners and suppliers to have different access rights to
your WeatherData API, assign the API to a product, and then use the Azure portal to
associate APIs with a product.
Applications that call a protected API must include a subscription key in every request.
You can regenerate these subscription keys at any time; for example, if you suspect that
a key has been shared with unauthorized users, you can create a new one.
23
Sandip Bhole
Enterprise Cloud Solution Architect
Every subscription has two keys - a primary key and a secondary key. Having two keys
makes it easier when you do need to regenerate a key. For example, if you want to change
the primary key and avoid downtime, use the secondary key in your apps.
For products in which subscriptions are enabled, clients must supply a key when making
calls to APIs in that product. Developers can obtain a key by submitting a subscription
request. If you approve the request, you must send them the subscription key securely,
for example, in an encrypted message. This step is a core part of the APIM workflow.
Applications must include a valid key in all HTTP requests that make calls to API endpoints
that are protected by a subscription. Keys can be passed in the request header or as a
query string parameter in the URL.
The default subscription key header name is Ocp-Apim-Subscription-Key, and the
default query string name is subscription-key.
To test out your API calls, you can use the developer portal, or command-line tools, such
as curl. Here's an example of a GET request using the developer portal, which shows the
subscription key header:
24
Sandip Bhole
Enterprise Cloud Solution Architect
Here's an example of how you would pass a key in a request header using curl:
BashCopy
curl --header "Ocp-Apim-Subscription-Key: <key string>" https://<apim gateway>.azure-
api.net/api/path
Here's an example of how you would use a curl command to pass a key as a query string
in a URL:
BashCopy
curl https://<apim gateway>.azure-api.net/api/path?subscription-key=<key string>
If the key isn't passed in the header, or as a query string in the URL, you'll get a 401 Access
Denied response from the API gateway.
You can use the Azure API Management (APIM) user interface in the Azure portal to create
subscriptions and obtain subscription keys for use in client apps.
Suppose your weather company has decided to make its meteorological data available to
clients that subscribe and pay for this service. The critical requirement is to only allow
access to clients that are allocated a key. As lead developer, you need to create an API
25
Sandip Bhole
Enterprise Cloud Solution Architect
gateway. You'll use the gateway to publish a RESTful Weather API that exposes an
OpenAPI endpoint. You'll then secure the endpoint and allocate a client key.
In this unit, you will:
• Publish a RESTful Weather API
• Deploy an API Management gateway
• Expose the Weather API through the gateway endpoint
• Restrict access based on a subscription key
You've developed a .NET Core app that returns weather information. The app includes
Swashbuckle to generate OpenAPI documentation.
To save time, let's start by running a script to host our API in Azure. The script performs
the following steps:
1. Run the following git clone command in Azure Cloud Shell to clone the repo
that contains the source for our app, and our setup script from GitHub.
Bash
git clone https://github.com/MicrosoftDocs/mslearn-control-
authentication-with-apim.git
Bash
cd mslearn-control-authentication-with-apim
3. As its name suggests, setup.sh is the script you'll run to create our API. It will
generate a public web app that exposes an OpenAPI interface.
26
Sandip Bhole
Enterprise Cloud Solution Architect
Bash
bash setup.sh
The script has seven parts and takes about a minute to run. Observe that,
during deployment, all dependencies needed for our app to run are
automatically installed on the remote App Service.
When the script has finished, it outputs two URLS, a Swagger URL, and an
Example URL. You can use these URLs to test the app deployment.
4. To test that our app deployed correctly, copy and paste the Swagger URL
from Azure Cloud Shell output into your favorite browser. The browser should
display the Swagger UI for our app, and declare the following RESTful
endpoints:
5. Finally, copy and save the Example URL from Azure Cloud Shell output. This
location is the Swagger JSON URL. You'll need it later in this exercise.
27
Sandip Bhole
Enterprise Cloud Solution Architect
The next step in this exercise is to create an API gateway in the Azure portal. In the next
exercise, you'll use this gateway to publish your API.
1. Sign into the Azure portal using the same account you activated the sandbox
with.
2. On the Azure resource menu or from the Home page, under Azure services,
select Create a resource. The Create a resource pane appears.
3. In the Search services and marketplace search bar, enter API Management,
and press Enter. The API Management pane appears.
4. Select Create. The Install API Management gateway pane appears.
5. On the Basics tab, enter the following values for each setting.
Setting Value
Project details
Subscription Concierge Subscription (default)
Resource From the dropdown list, select [sandbox resource group name].
group
Instance
details
Region Select from one of the following regions: North Central US, West US, West
Europe, North Europe, Southeast Asia, and Australia East. The
Consumption tier used in this exercise is only available in these regions.
Resource Enter apim-WeatherData<random number>; the random number is to ensure
name that the name is globally unique. Make a note of this resource name; it will
be the API gateway name that you'll need it later in this exercise.
Workspace Enter Weather-Company.
name
Administrator Enter your own email address.
email
Pricing tier
Pricing tier From the dropdown list, select Consumption.
Note
28
Sandip Bhole
Enterprise Cloud Solution Architect
You're using the Consumption tier because it is much faster to create while
testing. The overall experience is very similar to the other pricing tiers.
You can view the progress of the deployment, along with the resources that are being
created.
After deployment has completed, import the Weather API into the API Management
gateway by using the following procedure.
1. Select Go to resource. The Overview pane of the API Management
service for your resource appears.
2. In the left menu pane, under APIs, select APIs. The APIs pane for your API
Management service appears, with template selections for
creating/displaying an API.
3. Under Create from definition, select OpenAPI. The Create from OpenAPI
specification dialog box appears.
4. In the OpenAPI specification field, paste the Swagger JSON URL that you
saved earlier in the exercise. When you press Enter or select a different area
of the dialog box, other fields will be populated for you. This data is imported
from the OpenAPI specification that Swagger created.
5. Accept the defaults for all the other settings, and then select Create.
The Design tab of the Weather Data API displays all operations, which consists of two GET
operations.
29
Sandip Bhole
Enterprise Cloud Solution Architect
The final step is to add a subscription key for the Weather Data API.
1. In the left menu pane, under APIs, select Subscriptions.
The Subscriptions pane for your API Management service appears.
2. On the top menu bar, select Add subscription. The New subscription pane
appears.
Setting Value
Name weather-data-subscription
Display name Weather Data Subscription
Allow tracing No checkmark
Scope From the dropdown list, select API.
API From the dropdown list, select Weather Data.
4. Select Create. The Subscriptions pane lists two subscriptions, Built-in all-
access subscription and your Weather Data Subscription.
5. At the end of the Weather Data Subscription row, select the ellipsis, and in the
context menu select Show/hide keys. The Primary and Secondary key values
show.
6. Copy the Primary key from Weather Data Subscription to your clipboard and
save it in something like Notepad. You'll need this key in the next step.
The API is secured with a key. Now, we'll test the API without and with the key to
demonstrate secure access.
1. Make a request without passing a subscription key. In Azure Cloud Shell, run
the following cURL command. Substitute the [Name Of Gateway] placeholder
with the resource name for the API gateway (apim-WeatherDataNNNN) that
you created in the previous task.
Bash
curl -X GET https://[Name Of Gateway].azure-api.net/api/Weather/53/-1
30
Sandip Bhole
Enterprise Cloud Solution Architect
This command has no subscription key and should return a 401 Access
Denied error, similar to the following.
JSON
{ "statusCode": 401, "message": "Access denied due to missing
subscription key. Make sure to include subscription key when making
requests to an API." }
Azure
curl -X GET https://[Name Of Gateway].azure-api.net/api/Weather/53/-1 \
-H 'Ocp-Apim-Subscription-Key: [Primary Key]'
If you included the closing quote, this command should result in a successful
response similar to the following code.
JSON
{"mainOutlook":{"temperature":32,"humidity":34},"wind":{"speed":11,"direc
tion":239.0},"date":"2019-05-
16T00:00:00+00:00","latitude":53.0,"longitude":-1.0}
Certificates can be used to provide TLS mutual authentication between the client and the
API gateway. You can configure the API Management gateway to allow only requests with
certificates containing a specific thumbprint. The authorization at the gateway level is
handled through inbound policies.
For your meteorological app, you have some customers who have client certificates issued
by a certificate authority (CA) that you both trust. You want to allow those customers to
authenticate by passing those certificates.
Here, you'll learn how to configure API Management to accept client certificates.
31
Sandip Bhole
Enterprise Cloud Solution Architect
With TLS client authentication, the API Management gateway can inspect the certificate
contained within the client request and check for properties like:
Property Reason
Certificate Authority (CA) Only allow certificates signed by a particular CA.
Thumbprint Allow certificates containing a specified thumbprint.
Subject Only allow certificates with a specified subject.
Expiration Date Only allow certificates that haven't expired.
These properties aren't mutually exclusive and they can be combined to form your own
policy requirements. For example, you can specify that the certificate passed in the request
hasn't expired, and has been signed by a particular certificate authority.
Client certificates are signed to ensure that they aren't tampered with. When a partner
sends you a certificate, verify that it comes from them and not an imposter. There are two
common ways to verify a certificate:
• Check who issued the certificate. If the issuer was a certificate authority that
you trust, you can use the certificate. You can configure the trusted certificate
authorities in the Azure portal to automate this process.
• If the certificate is issued by a partner, verify that it came from them. For
example, if they deliver the certificate in person, you can be sure of its
authenticity. These certificates are known as self-signed certificates.
The Consumption tier in API Management is designed to conform with serverless design
principles. If you build your APIs from serverless technologies, such as Azure Functions,
this tier is a good fit. In the Consumption tier, you must explicitly enable the use of client
certificates, which you can do on the Custom domains pane. This step isn't necessary in
other tiers.
32
Sandip Bhole
Enterprise Cloud Solution Architect
Create these policies in the inbound processing policy file within the API Management
gateway.
Every client certificate includes a thumbprint, which is a hash, calculated from other
certificate properties. The thumbprint ensures that the values in the certificate haven't
been altered since the certificate was issued by the certificate authority. You can check
the thumbprint in your policy. The following example checks the thumbprint of the
certificate passed in the request.
33
Sandip Bhole
Enterprise Cloud Solution Architect
XML
<choose>
<when condition="@(context.Request.Certificate == null ||
context.Request.Certificate.Thumbprint != "desired-thumbprint")" >
<return-response>
<set-status code="403" reason="Invalid client certificate" />
</return-response>
</when>
</choose>
In the previous example, only one thumbprint would work so only one certificate would
be validated. Usually, each customer or partner company would pass a different certificate
with a different thumbprint. To support this scenario, obtain the certificates from your
partners, and use the Client certificates pane in the Azure portal to upload them to the
API Management resource. Then, add this code to your policy.
XML
<choose>
<when condition="@(context.Request.Certificate == null ||
!context.Request.Certificate.Verify() || !context.Deployment.Certificates.Any(c =>
c.Value.Thumbprint == context.Request.Certificate.Thumbprint))" >
<return-response>
<set-status code="403" reason="Invalid client certificate" />
</return-response>
</when>
</choose>
Check the issuer and subject of a client certificate
The following example checks the issuer and subject of the certificate passed in the
request.
XML
<choose>
<when condition="@(context.Request.Certificate == null ||
context.Request.Certificate.Issuer != "trusted-issuer" ||
context.Request.Certificate.SubjectName.Name != "expected-subject-name")" >
<return-response>
<set-status code="403" reason="Invalid client certificate" />
</return-response>
34
Sandip Bhole
Enterprise Cloud Solution Architect
</when>
</choose>
You configure API Management to accept client certificates by using inbound policies.
Suppose your weather company has decided to secure its API through certificate
authentication for certain clients who already use certificate authentication in other
systems. This setup will allow those clients to use existing certificates to authenticate
themselves against the API Management gateway.
In this unit, you'll:
First, use Cloud Shell to create a self-signed certificate, which you'll then use for
authentication between the client and the API Management gateway.
1. To create the private key and the certificate, run the following commands in
Cloud Shell.
Bash
pwd='Pa$$w0rd'
pfxFilePath='selfsigncert.pfx'
openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout
privateKey.key -out selfsigncert.crt -subj /CN=localhost
To make this example easy to follow, the preceding commands include the
password used to secure the private key. Whenever you generate a private
key for your own use, make sure you generate a secure password and control
access to it appropriately.
2. Now, convert the certificate to PEM format, which the curl tool can use, by
running these commands:
35
Sandip Bhole
Enterprise Cloud Solution Architect
Bash
openssl pkcs12 -export -out $pfxFilePath -inkey privateKey.key -in
selfsigncert.crt -password pass:$pwd
openssl pkcs12 -in selfsigncert.pfx -out selfsigncert.pem -nodes
Because you're using the Consumption tier for API Management, you must configure the
gateway to accept client certificates. Follow these steps.
1. From the Azure portal that is already open, select your API Management
service (apim-WeatherDataNNNN).
2. In the left menu pane, under Deployment and infrastructure,
select Custom domains. The Custom domains pane for your API
Management service appears.
3. For *Request client certificate, select Yes, and on the top menu bar,
select Save.
In this section, you'll configure API Management to accept a request only if it has a
certificate with a certain thumbprint (fingerprint). Let's get that thumbprint from the
certificate.
Note
36
Sandip Bhole
Enterprise Cloud Solution Architect
Bash
Fingerprint="$(openssl x509 -in selfsigncert.pem -noout -fingerprint)"
Fingerprint="${Fingerprint//:}"
echo ${Fingerprint#*=}
2. Copy the complete output (a hexadecimal string) and paste this fingerprint
value into a text file.
5. Replace the <inbound> node of the policy file with the following XML,
substituting the fingerprint you copied earlier for the desired-
fingerprint placeholder:
37
Sandip Bhole
Enterprise Cloud Solution Architect
XML
<inbound>
<choose>
<when condition="@(context.Request.Certificate == null ||
context.Request.Certificate.Thumbprint != "desired-fingerprint")" >
<return-response>
<set-status code="403" reason="Invalid client
certificate" />
</return-response>
</when>
</choose>
<base />
</inbound>
6. Select Save.
You can now test the new authentication policy with and without the certificate.
1. To test the API without the certificate, run the following command in Cloud
Shell, replacing the placeholder values with your API gateway name and
subscription key.
PowerShell
curl -X GET https://[api-gateway-name].azure-api.net/api/Weather/53/-1 \
-H 'Ocp-Apim-Subscription-Key: [Subscription Key]'
This command should return a 403 Client certificate error, and no data will be
returned.
2. In Cloud Shell, to test the API with the certificate, copy and paste the following
cURL command, using the primary subscription key from the first exercise
(you can also obtain this primary key from the Subscriptions pane for your
WeatherData API Management service). Remember to include your API
gateway name.
PowerShell
curl -X GET https://[api-gateway-name].azure-api.net/api/Weather/53/-1 \
-H 'Ocp-Apim-Subscription-Key: [subscription-key]' \
--cert-type pem \
--cert selfsigncert.pem
38
Sandip Bhole
Enterprise Cloud Solution Architect
JSON
{"mainOutlook":{"temperature":32,"humidity":34},"wind":{"speed":11,"direc
tion":239.0},"date":"2019-05-
16T00:00:00+00:00","latitude":53.0,"longitude":-1.0}
Summary
Our goal in this document was to help you evaluate whether Azure API Management is
appropriate for managing and publishing your organization's APIs. To help you make that
decision, we presented some criteria you can use:
• Number of APIs
• Rate of API changes
• API administration load
We applied these criteria in the context of our fictional food delivery organization. The
criteria helped you evaluate whether your organization's APIs would benefit from being
gathered under the umbrella of Azure API Management. You learned that in most
scenarios, Azure API Management offers the following benefits:
• Improved API standardization through enabling management of multiple
APIs from a single administrative interface.
• Enhanced centralization of all API operations by bringing multiple APIs under
a single administrative umbrella.
• Tightened API security resulting from permissions, access control policies,
and attack surface reduction.
However, you also learned that some organizations might not benefit from using Azure
API Management if they have:
• A relatively small number of deployed APIs.
• APIs that are mostly static or require few revisions.
• APIs that require few, if any, administrative extras such as policies, users, and
analytics.
The API economy—how API usage by developers and their consumers generates
important revenue streams for the companies that publish the APIs, increasingly drives
today's connected world. If you want to maximize your API economy, use the criteria in
this document to assess how Azure API Management can help your organization improve.
39
Sandip Bhole
Enterprise Cloud Solution Architect
Especially, its ability to adapt APIs to satisfy consumers, follow business trends, and take
advantage of new opportunities. The process you went through here should give you
enough information to choose the correct API lifecycle management solution for your
organization.
In this document, you've learned about API management and how you can control
authentication through subscriptions and certificate authentication. You've also learned
how the authentication models can be divided into granular levels of restrictions, offering
different authorization mechanisms to different clients.
40