How to create a WebPubSubServiceClient with .NET and Azure Identity

This how-to guide shows you how to create a WebPubSubServiceClient using Microsoft Entra ID in .NET.

Requirements

Sample codes

  1. Create a TokenCredential with Azure Identity SDK.

    using Azure.Identity;
    
    namespace chatapp
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                var credential = new DefaultAzureCredential();
            }
        }
    }
    

    credential can be any class that inherits from TokenCredential class.

    • EnvironmentCredential
    • ClientSecretCredential
    • ClientCertificateCredential
    • ManagedIdentityCredential
    • VisualStudioCredential
    • VisualStudioCodeCredential
    • AzureCliCredential

    To learn more, see Azure Identity client library for .NET

  2. Then create a client with endpoint, hub, and credential.

    using Azure.Identity;
    using Azure.Messaging.WebPubSub;
    
    public class Program
    {
        public static void Main(string[] args)
        {
            var credential = new DefaultAzureCredential();
            var client = new WebPubSubServiceClient(new Uri("<endpoint>"), "<hub>", credential);
        }
    }
    

    Or inject it into IServiceCollections with our BuilderExtensions.

    using System;
    
    using Azure.Identity;
    
    using Microsoft.Extensions.Azure;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    
    namespace chatapp
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddAzureClients(builder =>
                {
                    var credential = new DefaultAzureCredential();
                    builder.AddWebPubSubServiceClient(new Uri("<endpoint>"), "<hub>", credential);
                });
            }
        }
    }
    

    Learn how to use this client, see Azure Web PubSub service client library for .NET

Complete sample