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

将C#应用作为Windows服务运行时,如何登录Azure账户?

问题描述

我有一个需访问Azure才能运行的C#应用。本地运行时,先执行az login再启动应用就能正常工作,但将该应用作为Windows服务运行时,即便提前执行az login也无法正常工作。

事件监听器中获取的错误信息如下:

  • Visual Studio Token provider can't be accessed at C:\Windows\system32\config\systemprofile\AppData\Local.IdentityService\AzureServiceAuth\tokenprovider.json
  • Stored credentials not found. Need to authenticate user in VSCode Azure Account.
  • Please run 'az login' to set up account
  • PowerShell is not installed.
    ---> System.AggregateException: Multiple exceptions were encountered while attempting to authenticate. (EnvironmentCredential authentication unavailable. Environment variables are not fully configured.) (ManagedIdentityCredential authentication unavailable. The requested identity has not been assigned to this resource.
    Status: 400 (Bad Request)

请问是否有办法在应用作为Windows服务运行时完成Azure登录?

解决方案

1. 使用系统托管标识(生产环境推荐)

如果你的应用部署在Azure VM、VMSS或其他支持托管标识的Azure资源上,直接给服务所在的资源启用系统托管标识,再为该标识分配对应Azure资源的访问权限。应用无需手动登录,Azure SDK会自动获取令牌。

代码示例:

var credential = new ManagedIdentityCredential();
var client = new SomeAzureServiceClient(new Uri("https://your-resource.azure.com"), credential);

本地测试时,需安装Azure AD Managed Identity扩展,并确保服务运行账户拥有访问托管标识的权限。

2. 使用服务主体认证

创建Azure AD服务主体,为其分配所需Azure资源的权限,然后通过以下方式配置应用认证:

  • 环境变量方式(适配Windows服务):
    设置三个系统环境变量:

    • AZURE_CLIENT_ID:服务主体的客户端ID
    • AZURE_CLIENT_SECRET:服务主体的客户端密钥
    • AZURE_TENANT_ID:Azure租户ID

    代码中通过EnvironmentCredential自动读取变量:

    var credential = new EnvironmentCredential();
    var client = new SomeAzureServiceClient(new Uri("https://your-resource.azure.com"), credential);
    
  • 配置文件方式:
    在appsettings.json中存储服务主体信息:

    "AzureAd": {
      "ClientId": "your-client-id",
      "ClientSecret": "your-client-secret",
      "TenantId": "your-tenant-id"
    }
    

    代码中使用ClientSecretCredential加载配置:

    var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
    var credential = new ClientSecretCredential(
        config["AzureAd:TenantId"],
        config["AzureAd:ClientId"],
        config["AzureAd:ClientSecret"]);
    var client = new SomeAzureServiceClient(new Uri("https://your-resource.azure.com"), credential);
    

3. 为Windows服务运行账户执行az login(仅测试用)

Windows服务默认使用Local System账户,你之前执行的az login是在当前用户账户下,服务账户无法读取对应凭证。需切换到服务账户完成登录:

  1. 打开命令提示符,执行runas /user:NT Authority\System cmd.exe,启动System账户的命令行窗口
  2. 在该窗口中执行az login完成认证

此方式需定期重新登录更新凭证,不适合生产环境。

4. 使用用户分配托管标识

若系统托管标识不适用,可创建用户分配托管标识,将其分配给Windows服务所在机器,代码中指定该标识的客户端ID:

var credential = new ManagedIdentityCredential("user-assigned-identity-client-id");
var client = new SomeAzureServiceClient(new Uri("https://your-resource.azure.com"), credential);

内容的提问来源于stack exchange,提问作者Revanth Kariappa K R

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:50:22