.Net Project Graph SDK 令牌在部署到 Azure 应用服务时即将过期

问题描述 投票:0回答:1

我在 .Net 开发方面遇到了一些困难,并且在将其部署到 Azure 应用程序服务后陷入了我的 web 应用程序。

基本上,访问令牌似乎在 1 小时后过期,并且没有刷新并抛出错误:

ODataError:生命周期验证失败,令牌已过期。

目前我有一个名为 Invite.cshtml.cs 的类,如下所示:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Identity.Web;
using System.Text;
using System.Text.Json;
using System.ComponentModel.DataAnnotations;
using Azure.Identity;

namespace Test_Web_App.Pages
{
    [AuthorizeForScopes(ScopeKeySection = "MicrosoftGraph:Scopes")]
    public class InviteModel : PageModel
    {
        private readonly GraphServiceClient _graphServiceClient;
        private static ClientSecretCredential? _clientSecretCredential;
        private static GraphServiceClient? _appClient;
        private readonly HttpClient _httpClient;
        private readonly ILogger<IndexModel> _logger;
        private readonly IConfiguration _configuration;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public InviteModel(  ILogger<IndexModel> logger, IConfiguration configuration, GraphServiceClient graphServiceClient, HttpClient httpClient, IHttpContextAccessor httpContextAccessor)
        {
            _logger = logger;
            _graphServiceClient = graphServiceClient; ;
            _httpClient = httpClient; ;
            _configuration = configuration;
            _httpContextAccessor = httpContextAccessor;
        }

我注意到,这个调用不是从我的Azure WebApp调用的(但是当我在我的机器上本地运行该应用程序时确实运行),我认为这就是为什么当我运行我的应用程序时令牌永远不会刷新的原因:

public InviteModel(  ILogger<IndexModel> logger, IConfiguration configuration, GraphServiceClient graphServiceClient, HttpClient httpClient, IHttpContextAccessor httpContextAccessor)
        {
            _logger = logger;
            _graphServiceClient = graphServiceClient; ;
            _httpClient = httpClient; ;
            _configuration = configuration;
            _httpContextAccessor = httpContextAccessor;
        }

一旦尝试加载 graphServiceClient,代码就会在我的 OnPostAsync 方法上立即崩溃:

public async Task<IActionResult> OnPostAsync()
{
        var user = await _graphServiceClient.Me.GetAsync(); ;

老实说,我不知道我在这里缺少什么,因此非常感谢您能给我的任何帮助或指导。 提前非常感谢!

额外不确定这是否有帮助,但目前我的 Program.cs 中的内容如下:

var builder = WebApplication.CreateBuilder(args);

var initialScopes = builder.Configuration["AzureAd:Scopes"]?.Split(' ') ?? builder.Configuration["MicrosoftGraph:Scopes"]?.Split(' ');

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp( options =>
    {
        builder.Configuration.Bind("AzureAd", options);
        options.SaveTokens = true; // Ensure tokens are saved
    })
        .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
            .AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
            .AddInMemoryTokenCaches().AddMicrosoftGraph();
//Named HttpClient with IHttpClientFactory
builder.Services.AddTransient<GraphAuthorizationMessageHandler>();
builder.Services.AddHttpClient("GraphAPI",
        client => client.BaseAddress = new Uri(
            builder.Configuration.GetSection("MicrosoftGraph")["BaseUrl"] ??
                string.Empty))
    .AddHttpMessageHandler<GraphAuthorizationMessageHandler>();

builder.Services.AddScoped(sp => sp.GetService<IHttpClientFactory>().CreateClient("GraphAPI"));
builder.Services.AddHttpContextAccessor(); // Add this line to register IHttpContextAccessor
builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy.
    options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
app.Run();
c# asp.net-core microsoft-graph-sdks
1个回答
0
投票

万一将来有人需要,问题出在 azure Web 应用程序上。

我启用了应用服务身份验证。我通过修改这个 github bug 发现了它,其中一个开发人员提到了“Easy auth”: https://github.com/AzureAD/microsoft-identity-web/issues/2880

没有在任何地方找到此记录,因此留在这里供参考。

© www.soinside.com 2019 - 2024. All rights reserved.