You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从ASP.NET Core Blazor网站程序化管理Azure APIM用户与订阅并显示密钥?

Absolutely, this is totally feasible! You can build this functionality directly into your ASP.NET Core Blazor app without relying on the Azure Portal at all. Let's break down how to do this, including the tools you'll need and key implementation steps:

Available Libraries & Tools

The official, recommended tool for this is the Azure.ResourceManager.ApiManagement NuGet package. It's part of Azure's .NET SDK for managing resources, and it provides strongly-typed methods to interact with every part of Azure API Management—including creating users, subscriptions, and retrieving subscription keys.

You'll also need the Azure.Identity package to handle authentication to Azure's management API from your Blazor app.

Step-by-Step Implementation Overview

1. Set Up Azure Authentication

First, your app needs permission to manage your APIM instance. Create a Service Principal in Azure AD, then assign it an RBAC role like ApiManagement Contributor (or a custom role with only the permissions you need: Microsoft.ApiManagement/service/users/write, Microsoft.ApiManagement/service/subscriptions/write, Microsoft.ApiManagement/service/subscriptions/listSecrets/action).

In your Blazor app, use DefaultAzureCredential (from Azure.Identity) to authenticate the service principal. This works with environment variables, managed identity, or local development credentials (like Azure CLI).

2. Install Required Packages

Add these NuGet packages to your project:

dotnet add package Azure.ResourceManager.ApiManagement
dotnet add package Azure.Identity

3. Create an APIM User

Inject the ApiManagementClient into your Blazor component (or a backend service) and use it to create a user. Here's a quick example (Blazor Server):

using Azure.ResourceManager.ApiManagement;
using Azure.ResourceManager.ApiManagement.Models;
using Azure.Identity;

// Initialize the client
var credential = new DefaultAzureCredential();
var subscriptionId = "your-azure-subscription-id";
var apiManagementClient = new ApiManagementClient(credential, subscriptionId);

// Create user parameters
var userCreateParameters = new UserCreateOrUpdateContent(
    email: "user@example.com",
    firstName: "John",
    lastName: "Doe")
{
    Note = "Created via Blazor app"
};

// Create the user in APIM
var resourceGroupName = "your-resource-group";
var serviceName = "your-apim-service-name";
var userId = "unique-user-id"; // Can be a GUID or user's email hash

var user = await apiManagementClient.Users.CreateOrUpdateAsync(
    resourceGroupName,
    serviceName,
    userId,
    userCreateParameters);

4. Create a Subscription for the User

Once the user exists, create a subscription tied to them and an APIM product:

var subscriptionCreateParameters = new SubscriptionCreateOrUpdateContent(
    userId: user.Value.Id,
    productId: "/subscriptions/{subscriptionId}/resourceGroups/{rg}/providers/Microsoft.ApiManagement/service/{apim}/products/{product-name}")
{
    DisplayName = "User's Premium Subscription",
    State = SubscriptionState.Active
};

var subscription = await apiManagementClient.Subscriptions.CreateOrUpdateAsync(
    resourceGroupName,
    serviceName,
    "unique-subscription-id", // Or let APIM generate one
    subscriptionCreateParameters);

5. Retrieve & Display Subscription Keys

To get the subscription keys, use the ListSecretsAsync method. You can then display these in your Blazor component (with security precautions):

var subscriptionSecrets = await apiManagementClient.Subscriptions.ListSecretsAsync(
    resourceGroupName,
    serviceName,
    subscription.Value.Name);

// Access primary and secondary keys
var primaryKey = subscriptionSecrets.Value.PrimaryKey;
var secondaryKey = subscriptionSecrets.Value.SecondaryKey;

In your Blazor component, you might display them like this (with optional masking):

<div class="subscription-keys">
    <p>Primary Key: @MaskKey(primaryKey)</p>
    <p>Secondary Key: @MaskKey(secondaryKey)</p>
    <button @onclick="() => CopyToClipboard(primaryKey)">Copy Primary Key</button>
</div>

@code {
    private string MaskKey(string key)
    {
        if (string.IsNullOrEmpty(key)) return string.Empty;
        return $"{key.Substring(0, 4)}***{key.Substring(key.Length - 4)}";
    }

    private async Task CopyToClipboard(string text)
    {
        await Clipboard.SetTextAsync(text);
        // Show success toast
    }
}
Key Security & Implementation Notes
  • Minimize Permissions: Don't assign broader roles than needed. Use a custom RBAC role that only allows creating users, subscriptions, and listing secrets.
  • Avoid Exposing Credentials: If you're using Blazor WebAssembly, never handle the service principal credentials in the client. Instead, create a backend API endpoint in your ASP.NET Core app that handles the APIM calls, and have the WASM app call your backend.
  • Secret Handling: Subscription keys are sensitive. Only display them to authenticated users who own the subscription, and avoid logging or storing them in plaintext.
  • Error Handling: Add try/catch blocks around APIM calls to handle scenarios like duplicate users, invalid product IDs, or permission errors—give users clear, friendly feedback.
Blazor-Specific Tips
  • Blazor Server: This is the simpler, more secure option since all APIM calls run server-side, and credentials never leave your backend.
  • Blazor WebAssembly: Use your ASP.NET Core host as a proxy. The WASM app sends requests to your backend, which then calls the APIM management API using the service principal.

内容的提问来源于stack exchange,提问作者Umang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 15:32:44