0

Going to have a web api that calls another web api requiring the OAuth client credential flow. The web api does not need authentication.

Should I use MSAL.NET instead of Microsoft.Identity.Web in this case?

I have read https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-net-migration-confidential-client?tabs=authcode and https://github.com/AzureAD/microsoft-identity-web/wiki/web-apis, but they do not provide a clear answer.

1 Answers1

0

Referencing this document MSAL.NET or Microsoft.Identity.Web. You should use Microsoft.Identity.Web. Protecting api with azure is not complicated.

  1. Login to Azure, choose azure active directory. remember your primary domain.
    enter image description here
    enter image description here

  2. Choose app registrations - new registration - input whatever name and continue. Remember its client ID.
    enter image description here

  3. Choose expose an api, then click set . Then save and remember this application ID URI.
    enter image description here

  4. Choose Ceritificates and Secrets, add new client secret, copy and remember the secret value right away.
    enter image description here

  5. You can try with this console client to get a token and access webapi. modify the client ID ,client secret to yours, make the scope equals to your application ID URI + "/.default" .Don't forget install IdentityModel package.

using IdentityModel.Client;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;

internal class Program
{
    private static async Task Main(string[] args)
    {
        // request for token
        var client = new HttpClient();
        var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
        {
            Address = "https://login.microsoftonline.com/6c1ec436-4626-4a07-836f-0510d13f5c6b/oauth2/v2.0/token",
            ClientId = "your client ID",
            ClientSecret = "your client secrect",
            Scope = "{your application ID URI}/.default"
        });

        if (tokenResponse.IsError)
        {
            Console.WriteLine(tokenResponse.Error);
            return;
        }

        Console.WriteLine(tokenResponse.Json);


        // using token to access API
        var apiClient = new HttpClient();
        apiClient.SetBearerToken(tokenResponse.AccessToken);

        var response = await apiClient.GetAsync("https://localhost:7171/weatherforecast");
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.StatusCode);
        }
        else
        {
            var content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(JArray.Parse(content));
        }

    }
}
  1. Run this client, remember the token you get, decode it in JWT.IO ,remember the iss value. enter image description here enter image description here
  2. Create a webapi, use "[Authorize]" attribute on your api. In the program.cs file . add authentication & authorize services. Make the authority equals to the iss value you just decoded.
builder.Services.AddAuthentication("Bearer")
        .AddJwtBearer("Bearer", options =>
        {
            options.Authority = "{the decoded iss value}";

            options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false
                };
         });
builder.Services.AddAuthorization();

Don't forget app.UseAuthorization(); Run your api and client, you can find you can only access this api using this azure token using the client credential flow.

Qiang Fu
  • 1,401
  • 1
  • 2
  • 8