Call an ASP.NET Core web API with cURL
This article shows you how to call a protected ASP.NET Core web API using Client URL (cURL). cURL is a command line tool that developers use to transfer data to and from a server. In this article, you register a web app and a web API in a tenant. The web app is used to get an access token generated by the Microsoft identity platform. Next, you use the token to make an authorized call to the web API using cURL.
This article shows you how to call a protected ASP.NET Core web API using Client URL (cURL). cURL is a command line tool that developers use to transfer data to and from a server. Following on from the Tutorial: Implement a protected endpoint to your API, where you created a protected API, you need to register a web application with the Microsoft identity platform to generate an access token. Next, you use the token to make an authorized call to the API using cURL.
Prerequisites
- An Azure account with an active subscription. Create an account.
- This Azure account must have permissions to manage applications. Any of the following Microsoft Entra roles include the required permissions:
- Application Administrator
- Application Developer
- Cloud Application Administrator
- Download and install cURL on your workstation computer.
- A minimum requirement of .NET 8.0 SDK.
- An Azure account with an active subscription. Create an account.
- This Azure account must have permissions to manage applications. Any of the following Microsoft Entra roles include the required permissions:
- Application Administrator
- Application Developer
- Cloud Application Administrator
- Completion of the tutorial series:
- Download and install cURL on your workstation computer.
Register an application with the Microsoft identity platform
The Microsoft identity platform requires your application to be registered before providing identity and access management services. The application registration allows you to specify the name, and type of the application, and the sign-in audience. The sign-in audience specifies what types of user accounts are allowed to sign-in to a given application.
Register the web API
Tip
Steps in this article might vary slightly based on the portal you start from.
Follow these steps to create the web API registration:
Sign in to the Microsoft Entra admin center as at least an Application Developer.
If you have access to multiple tenants, use the Settings icon in the top menu to switch to the tenant in which you want to register the application from the Directories + subscriptions menu.
Browse to Identity > Applications > App registrations.
Select New registration.
Enter a Name for the application, such as NewWebAPI1.
For Supported account types, select Accounts in this organizational directory only. For information on different account types, select Help me choose option.
Select Register.
The application's Overview pane is displayed when registration is complete. Record the Directory (tenant) ID and the Application (client) ID to be used in your application source code.
Note
The Supported account types can be changed by referring to Modify the accounts supported by an application.
Expose the API
Once the API is registered, you can configure its permission by defining the scopes that the API exposes to client applications. Client applications request permission to perform operations by passing an access token along with its requests to the protected web API. The web API then performs the requested operation only if the access token it receives is valid.
Under Manage, select Expose an API > Add a scope. Accept the proposed Application ID URI
(api://{clientId})
by selecting Save and continue. The{clientId}
is the value recorded from the Overview page. Then enter the following information:- For Scope name, enter
Forecast.Read
. - For Who can consent, ensure that the Admins and users option is selected.
- In the Admin consent display name box, enter
Read forecast data
. - In the Admin consent description box, enter
Allows the application to read weather forecast data
. - In the User consent display name box, enter
Read forecast data
. - In the User consent description box, enter
Allows the application to read weather forecast data
. - Ensure that the State is set to Enabled.
- For Scope name, enter
Select Add scope. If the scope has been entered correctly, it'll be listed in the Expose an API pane.
Register the web app
Having a web API isn't enough however, as a web app is also needed to obtain an access token to access the web API you've created.
Follow these steps to create the web app registration:
- Select Home to return to the home page. Browse to Identity > Applications > App registrations.
- Select New registration.
- Enter a Name for the application, such as
web-app-calls-web-api
. - For Supported account types, select Accounts in this organizational directory only. For information on different account types, select the Help me choose option.
- Under Redirect URI (optional), select Web, and then enter
http://localhost
in the URL text box. - Select Register.
- Sign in to the Microsoft Entra admin center as at least an Application Developer.
- If you have access to multiple tenants, use the Settings icon in the top menu to switch to the tenant in which you want to register the application from the Directories + subscriptions menu.
- Browse to Identity > Applications > App registrations.
- Select New registration.
- Enter a Name for the application, such as
web-app-calls-web-api
. - For Supported account types, select Accounts in this organizational directory only. For information on different account types, select the Help me choose option.
- Under Redirect URI (optional), select Web, and then enter
http://localhost
in the URL text box. - Select Register.
When registration is complete, the app registration is displayed on the Overview pane. Record the Directory (tenant) ID and the Application (client) ID to be used in later steps.
Add a client secret
A client secret is a string value your app can use to identity itself, and is sometimes referred to as an application password. The web app uses the client secret to prove its identity when it requests tokens.
Follow these steps to configure a client secret:
From the Overview pane, under Manage, select Certificates & secrets > Client secrets > New client secret.
Add a description for your client secret, for example My client secret.
Select an expiration for the secret or specify a custom lifetime.
- A client secret's lifetime is limited to two years (24 months) or less. You can't specify a custom lifetime longer than 24 months.
- Microsoft recommends that you set an expiration value of less than 12 months.
Select Add.
Be sure to record the Value of the client secret. This secret value is never displayed again after you leave this page.
Add application permissions to allow access to a web API
By specifying a web API's scopes in the web app registration, the web app can obtain an access token containing the scopes provided by the Microsoft identity platform. Within the code, the web API can then provide permission-based access to its resources based on the scopes found in the access token.
Follow these steps to configure the web app permissions to the web API:
- From the Overview pane of your web application (web-app-that-calls-web-api), under Manage, select API permissions > Add a permission > APIs my organization uses.
- Select NewWebAPI1 or the API that you wish to add permissions to.
- Under Select permissions, check the box next to Forecast.Read. You may need to expand the Permission list. This selects the permissions the client app should have on behalf of the signed-in user.
- Select Add permissions to complete the process.
After adding these permissions to your API, you should see the selected permissions under Configured permissions.
You may also notice the User.Read permission for the Microsoft Graph API. This permission is added automatically when you register an app.
Test the web API
Clone the ms-identity-docs-code-dotnet repository.
git clone https://github.com/Azure-Samples/ms-identity-docs-code-dotnet.git
Navigate to
ms-identity-docs-code-dotnet/web-api
folder and open./appsettings.json
file, replace the{APPLICATION_CLIENT_ID}
and{DIRECTORY_TENANT_ID}
with:{APPLICATION_CLIENT_ID}
is the web API Application (client) ID on the app's Overview pane App registrations.{DIRECTORY_TENANT_ID}
is the web API Directory (tenant) ID on the app's Overview pane App registrations.
Execute the following command to start the app:
An output similar to the following will appear. Record the port number in the
https://localhost:{port}
URL.... info: Microsoft.Hosting.Lifetime[14] Now listening on: https://localhost:{port} ...
Test the web API
Navigate to the web API that was created in Tutorial: Create an ASP.NET Core project and configure the API, for example NewWebAPILocal, and open the folder.
Open a new terminal window and navigate to the folder where the web API project is located.
An output similar to the following will appear. Record the port number in the
https://localhost:{port}
URL.... info: Microsoft.Hosting.Lifetime[14] Now listening on: https://localhost:{port} ...
Request an authorization code
The authorization code flow begins with the client directing the user to the /authorize
endpoint. In this request, the client requests the Forecast.Read
permission from the user.
https://login.partner.microsoftonline.cn/{tenant_id}/oauth2/v2.0/authorize?client_id={web-app-calls-web-api_application_client_id}&response_type=code&redirect_uri=http://localhost&response_mode=query&scope=api://{web_API_application_client_id}/Forecast.Read
Copy the URL, replace the following parameters and paste it into your browser:
{tenant_id}
is the web app Directory (tenant) ID.{web-app-calls-web-api_application_client_id}
is the Application (client) ID on the web app's (web-app-calls-web-api) Overview pane.{web_API_application_client_id}
is the Application (client) ID on the web API's (NewWebAPI1) Overview pane.
Sign in as a user in the Microsoft Entra tenant in which the apps are registered. Consent to any requests for access, if necessary.
Your browser will be redirected to
http://localhost/
. Refer to your browser's navigation bar and copy the{authorization_code}
to use in the following steps. The URL takes the form of the following snippet:http://localhost/?code={authorization_code}
Use an authorization code and cURL to get an access token
cURL can now be used to request an access token from the Microsoft identity platform.
Copy the cURL command in the following snippet. Replace the values in parentheses with the following parameters to your terminal. Be sure to remove the parentheses:
curl -X POST https://login.partner.microsoftonline.cn/{tenant_id}/oauth2/v2.0/token \ -d 'client_id={web-app-calls-web-api_application_client_id}' \ -d 'api://{web_API_application_client_id}/Forecast.Read' \ -d 'code={authorization_code}&session_state={web-app-calls-web-api_application_client_id}' \ -d 'redirect_uri=http://localhost' \ -d 'grant_type=authorization_code' \ -d 'client_secret={client_secret}'
{tenant_id}
is the web app Directory (tenant) ID.client_id={web-app-calls-web-api_application_client_id}
, andsession_state={web-app-calls-web-api_application_client_id}
is the Application (client) ID on the web application's (web-app-calls-web-api) Overview pane.api://{web_API_application_client_id}/Forecast.Read
is the Application (client) ID on the web API's (NewWebAPI1) Overview pane.code={authorization_code}
is the authorization code that was received in Request an authorization code. This enables the cURL tool to request an access token.client_secret={client_secret}
is the client secret Value recorded in Add a client secret.
Run the cURL command and if entered correctly, you should receive a JSON response similar to the following output:
{ "token_type": "Bearer", "scope": "api://{web_API_application_client_id}/Forecast.Read", "expires_in": 3600, "ext_expires_in": 3600, "access_token": "{access_token}" }
Call web API with access token
By running the previous cURL command, the Microsoft identity platform has provided an access token. The acquired token can now be used as a bearer in an HTTP request to call the web API.
To call the web API, copy the following cURL command, replace the following values in parentheses and paste it into your terminal:
curl -X GET https://localhost:{port}/weatherforecast -ki \ -H 'Content-Type: application/json' \ -H "Authorization: Bearer {access_token}"
{access_token}
the access token value recorded from the JSON output in the previous section.{port}
the port number from the web API recorded when running the API in the terminal. Ensure it's thehttps
port number.
With a valid access token included in the request, the expected response is
HTTP/2 200
with output similar to the following output:HTTP/2 200 content-type: application/json; charset=utf-8 date: Day, DD Month YYYY HH:MM:SS server: Kestrel [{"date":"YYYY-MM-DDTHH:MM:SS","temperatureC":36,"summary":"Hot","temperatureF":96},{"date":"YYYY-MM-DDTHH:MM:SS","temperatureC":43,"summary":"Warm","temperatureF":109},{"date":"YYYY-MM-DDTHH:MM:SS","temperatureC":18,"summary":"Warm","temperatureF":64},{"date":"YYYY-MM-DDTHH:MM:SS","temperatureC":50,"summary":"Chilly","temperatureF":121},{"date":"YYYY-MM-DDTHH:MM:SS","temperatureC":3,"summary":"Bracing","temperatureF":37}]
Next steps
For more information about OAuth 2.0 authorization code flow and application types, see: