How do i protect Web API

Keith Viking 20 Reputation points
2023-05-02T15:38:45.8333333+00:00

Hi

I'm taking some training courses on Azure and Web API.

I need to protect my Web Api which has been built on Visual Studio 2022 with all the latest versions, updates installed and selected (except i didnt select .Net 7).

I saw these samples

https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2

but i dont know which one i need to select and use for my basis.

I need to have the Api protected so a user does not need to login but rather the application takes care of that utilising oauth2.

I have read, it maybe Identity Server i need to use or Azure and register an app however the courses and books i have display completely different options and layouts.

Please could someone guide me, what to do in order to have Identity, Azure setup for this requirement (token based i presume) and which project i should select from the above repository to get started protecting my Web API.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,515 questions
Azure Role-based access control
Azure Role-based access control
An Azure service that provides fine-grained access management for Azure resources, enabling you to grant users only the rights they need to perform their jobs.
791 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
331 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
21,375 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 64,161 Reputation points
    2023-05-02T15:52:06.3866667+00:00

    the samples you link to all have different features.

    sample 4 is the one you want. it has both a client web site that uses oauth login and a sample web api site that uses jwt bearer tokens. the variants are for if the client is in your ad, a business to business ad, or a multi-tenant ad.

    all the sample uses azure ad and require you have an azure ad account.


  2. Tiny Wang-MSFT 2,486 Reputation points Microsoft Vendor
    2023-05-03T07:17:15.8366667+00:00

    Hi @Keith Viking , first of all, this is the tutorial for using Azure AD to protect the Web API. Here's the detailed steps of what we need to do.

    1. Going to Azure AD to register an Azure AD app, no need to set redirect URL.
    2. Create a client secret for authorization, copy and save the secret value here.

    User's image

    1. Exposing an API, since you don't want a user to sign in, so you have to use client credential flow to generate access token, therefore you need to create a role instead of creating a scope.

    User's image

    User's image

    1. Add API permission.

    User's image

    User's image

    User's image

    1. Change Web API code. For a new .net 7 web API, having code below in the Program.cs, and add configurations in appsettings.json. Don't forget to add [Authorize] attribute in Controller.
    using Microsoft.Identity.Web;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    
    builder.Services.AddControllers();
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
    
    builder.Services.AddEndpointsApiExplorer();
    ....
    ....
    app.UseHttpsRedirection();
    app.UseAuthentication();
    app.UseAuthorization();
    
    
    "AzureAd": {
        "Instance": "https://login.microsoftonline.com/",
        "ClientId": "azure_ad_app_client_id",
        "ClientSecret": "client_secret",
        "Domain": "tenant_id",
        "TenantId": "tenant_id", 
        "Audience": "api://client_id"
      },
    
    1. Generate access token and calling the Web API. We can use code below to generate access token. We can also send http request to generate the token.
    using Azure.Identity;
    
    var scopes = new[] { "https://client_id/.default" };
    var tenantId = "tenant_name.onmicrosoft.com";
    var clientId = "your_azuread_clientid";
    var clientSecret = "client_secret";
    var clientSecretCredential = new ClientSecretCredential(
        tenantId, clientId, clientSecret);
    var tokenRequestContext = new TokenRequestContext(scopes);
    var token = clientSecretCredential.GetTokenAsync(tokenRequestContext).Result.Token;
    
    //or send post request
    POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token HTTP/1.1 
    Content-Type: application/x-www-form-urlencoded 
    client_id=azure_ad_client_id
    &scope=https://client_id/.default 
    &client_secret=client_secret
    &grant_type=client_credentials
    

    User's image

    Finally using the token we got to call the web API:

    User's image

    =============================================

    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,

    TinyWang


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.