Muokkaa

Jaa


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 for free.
  • 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.

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:

  1. Sign in to the Microsoft Entra admin center as at least an Application Developer.

  2. 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.

  3. Browse to Identity > Applications > App registrations.

  4. Select New registration.

  5. Enter a Name for the application, such as NewWebAPI1.

  6. For Supported account types, select Accounts in this organizational directory only. For information on different account types, select Help me choose option.

  7. Select Register.

    Screenshot that shows how to enter a name and select the account type.

  8. 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.

    Screenshot that shows the identifier values on the overview page.

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.

  1. 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:

    1. For Scope name, enter Forecast.Read.
    2. For Who can consent, ensure that the Admins and users option is selected.
    3. In the Admin consent display name box, enter Read forecast data.
    4. In the Admin consent description box, enter Allows the application to read weather forecast data.
    5. In the User consent display name box, enter Read forecast data.
    6. In the User consent description box, enter Allows the application to read weather forecast data.
    7. Ensure that the State is set to Enabled.
  2. Select Add scope. If the scope has been entered correctly, it'll be listed in the Expose an API pane.

    Screenshot that shows the field values when adding the scope to an API.

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:

  1. Select Home to return to the home page. Browse to Identity > Applications > App registrations.
  2. Select New registration.
  3. Enter a Name for the application, such as web-app-calls-web-api.
  4. For Supported account types, select Accounts in this organizational directory only. For information on different account types, select the Help me choose option.
  5. Under Redirect URI (optional), select Web, and then enter http://localhost in the URL text box.
  6. Select Register.
  1. Sign in to the Microsoft Entra admin center as at least an Application Developer.
  2. 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.
  3. Browse to Identity > Applications > App registrations.
  4. Select New registration.
  5. Enter a Name for the application, such as web-app-calls-web-api.
  6. For Supported account types, select Accounts in this organizational directory only. For information on different account types, select the Help me choose option.
  7. Under Redirect URI (optional), select Web, and then enter http://localhost in the URL text box.
  8. 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:

  1. From the Overview pane, under Manage, select Certificates & secrets > Client secrets > New client secret.

  2. Add a description for your client secret, for example My client secret.

  3. 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.
  4. Select Add.

  5. 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:

  1. 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.
  2. Select NewWebAPI1 or the API that you wish to add permissions to.
  3. 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.
  4. 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

  1. Clone the ms-identity-docs-code-dotnet repository.

    git clone https://github.com/Azure-Samples/ms-identity-docs-code-dotnet.git 
    
  2. 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.
  3. Execute the following command to start the app:

    dotnet run
    
  4. 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

  1. 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.

  2. Open a new terminal window and navigate to the folder where the web API project is located.

  1. Execute the following command to start the app:

    dotnet run
    
  1. 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.microsoftonline.com/{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
  1. 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.
  2. Sign in as a user in the Microsoft Entra tenant in which the apps are registered. Consent to any requests for access, if necessary.

  3. 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.

  1. 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.microsoftonline.com/{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}, and session_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.
  2. 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.

  1. 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 the https port number.
  2. 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: