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

使用C#/.NET续期Microsoft Graph API订阅时遇未授权错误

编程续期Microsoft Graph API订阅时遇“订阅不属于当前应用”错误

尝试通过代码续期Microsoft Graph API订阅,已确认client id、subscription id、client secret和tenant id均正确,但运行代码时出现以下错误:

结果:无法续期订阅,订阅ID为IvyRehab.Workday.Automations.Functions.Services.GraphCredentials
异常:Microsoft.Graph.Models.ODataErrors.ODataError: 操作:Update;异常:[状态码:Unauthorized;原因:Unauthorized;消息:订阅不属于当前应用。]

续期代码

public async Task RenewSubscription(Subscription subscription)
{
    if (subscription.ExpirationDateTime is null)
        throw new ArgumentNullException(nameof(subscription.ExpirationDateTime));

    try
    {
        await graphServiceClient.Subscriptions[_graphCredentials.SubscriptionId].PatchAsync(subscription);
        _logger.LogInformation("Subscription has been renewed to {newDate}", subscription.ExpirationDateTime.ToString());
    }
    catch (Exception exception)
    {
        _logger.LogError(exception, "Failed to renew subscription with subscription id {subscriptionId}", _graphCredentials);
    }
}

已在Azure门户的API权限中启用了User.Read和Subscription.Read.All权限,尝试过调整权限、设置访问密钥等操作,能够拉取订阅及用户等实体信息,但仅在尝试更新过期时间时遇到此问题。


2024年9月27日更新

尝试获取当前凭证关联的所有订阅,返回结果为空列表:

测试代码

public class TestRenewal
{
    private readonly ILogger<TestRenewal> _logger;
    private readonly IGraphSubscriptionService _graphSubscriptionService;
    private readonly IUserService _userService;
    private readonly GraphServiceClient _graphServiceClient;

    public TestRenewal(
        ILogger<TestRenewal> logger,
        IGraphSubscriptionService graphSubscriptionService,
        IUserService userService,
        IOptions<GraphCredentials> graphCredentials)
    {
        _logger = logger;
        _graphSubscriptionService = graphSubscriptionService;
        _userService = userService;

        var credentials = graphCredentials?.Value ?? throw new ArgumentNullException(nameof(graphCredentials));
        var clientSecretCredential = new ClientSecretCredential(
            credentials.TenantId,
            credentials.ClientId,
            credentials.ClientSecret
        );

        _graphServiceClient = new GraphServiceClient(clientSecretCredential, new[] { "https://graph.microsoft.com/.default" });
}

    [Function("Function")]
    public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req)
    {
        try
        {
            _logger.LogInformation("Getting subscriptions");
            var result = await _graphServiceClient.Subscriptions.GetAsync();
            _logger.LogInformation("Subscriptions retrieved");
            _logger.LogInformation(JsonConvert.SerializeObject(result));
            return new OkObjectResult(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to fetch subscriptions.");
            return new OkObjectResult("");
        }
    }
}

日志输出

[2024-09-27T15:13:41.915Z] {"Value":[],"AdditionalData":{"@odata.context":"https://graph.microsoft.com/v1.0/$metadata#subscriptions"},"BackingStore":{"ReturnOnlyChangedValues":false,"InitializationCompleted":true},"OdataCount":null,"OdataNextLink":null}
[2024-09-27T15:13:43.914Z] Executing OkObjectResult, writing value of type 'Microsoft.Graph.Models.SubscriptionCollectionResponse'.

再次确认凭证均正确,该订阅是几天前创建的Entra合作伙伴主题。


2024年9月30日更新

按照建议获取所有订阅仍无结果,但通过代码创建的订阅可正常显示。经同事用Graph Explorer查询发现,门户创建的订阅关联的是Azure门户的Client Id,而非我的应用Client Id。因此若要通过代码续期订阅,需先通过代码创建订阅。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 19:53:14