microsoftgraph / microsoftgraph/msgraph-sdk-dotnet

.Net Project Graph SDK Token is expiring when deployed to Azure App Service

Open
#2,723 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Needs: Attention :wave: type:bug
Dominant language
C#
Stars
789
Forks
264
Avg merge
15h 17m
Merged PRs (30d)
3

Description

Describe the bug

I developed a .NET webapp and after deploying it into Azure App servicey the access token seems to be expiring after 1h and not refreshing and throwing me the error:

ODataError: Lifetime validation failed, the token is expired.

Currently I have a class called Invite.cshtml.cs that looks like this:

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

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

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

The code after 1 hour of the user being signed in throws a server error for token expiration on my OnPostAsync method as soon as it tries to load the graphServiceClient:

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

On my Program.cs I have setup the following:

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)
            .AddInMemoryTokenCaches().AddMicrosoftGraph();

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();
Expected behavior

I expected the builder settings in Program.cs to automatically refresh the Access token since they are using graph sdk

How to reproduce
  • Create builder for Initialize GraphServiceClient.
  • Create class to send call to graphServiceClient (e.g., graphServiceClient.Me.GetAsync(); )
  • Publish application to Azure Web App
  • Open Azure Web app trigger Post method.
  • Wait 1 hour for token to expire and trigger post method again
SDK Version

5.56.0

Latest version known to work for scenario above?

No response

Known Workarounds

N/A

Debug output
Click to expand log ```
</details>


### Configuration

Windows 11
x64

### Other information

_No response_

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with Program.cs and Invite.cshtml.cs, then review the token acquisition and GraphServiceClient setup used by the deployed Azure App Service. Reproduce the issue by calling OnPostAsync after the reported one-hour interval and inspect the token or authentication behavior. Done means the Graph request succeeds after the access token expires without the lifetime validation error.

Written by the indexing model from the issue text.

Assessment

Tech stack
azure, csharp
Domain
api, authentication, cloud
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.