Home > OS >  .Net Core Graph API Token Issue - "Access token has expired or is not yet valid"
.Net Core Graph API Token Issue - "Access token has expired or is not yet valid"

Time:02-24

I am developing a .Net 6 application, hosted in an Azure App Service and using Azure AD Authentication.

When viewing a Request page, I would like to check if the user belongs to an Azure Ad Group. This works sometimes, but users will periodically get an error when trying to view the page: "Access token has expired or is not yet valid."

I assume the token is being expired as if the user clears their cookies, AAD will re-authenticate them creating a new token and all is fine again, but but I haven't been able to find anything around refreshing tokens and am not sure where to go from here.

Has anyone experienced this behaviour and found a solution for it?

Here are some relevant sections of the code

Startup.cs File:

        string[] initialScopes = Configuration.GetValue<string>("GraphAPI:Scopes")?.Split(' ');

        services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
            .EnableTokenAcquisitionToCallDownstreamApi(options =>
            {
                Configuration.Bind("AzureAd", options);
            }, initialScopes)
           .AddInMemoryTokenCaches()
           .AddMicrosoftGraph(options =>
           {
               options.Scopes = String.Join(' ', initialScopes);
           });
           

AADGroupFunctions.cs

        AADGroupFunctions.cs

        private readonly GraphServiceClient _graphServiceClient;

        public AADGroupFunctions(GraphServiceClient graphServiceClient)
        {
            _graphServiceClient = graphServiceClient;
        }

        public async Task<List<IADLookupModel>> FindUsersInGroup(string groupId)
        {
            var listOfUsers = new List<IADLookupModel>();
            var filterString = $"startswith(mail, '{groupId}')";
            var groups = await _graphServiceClient.Groups
                              .Request()
                              .Header("ConsistencyLevel", "eventual")
                              .Filter(filterString)
                              .Expand("members")
                              .Top(1)
                              .GetAsync();

            if (groups.Any())
            {
                if (groups.First().Members.Any())
                {
                    foreach (Microsoft.Graph.User user in groups.First().Members)
                    {
                        try
                        {
                            var mail = "";
                            if (user.Mail != null)
                            {
                                mail = user.Mail.ToLower();

                                listOfUsers.Add(new UserModel()
                                {
                                    DisplayName = user.DisplayName,
                                    UPN = user.UserPrincipalName.ToLower(),
                                    Email = mail,
                                    Description = user.JobTitle ?? ""
                                });
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }

            return listOfUsers;
        }

           

Error Message when trying to call the FindUsersInGroup() function:

            An unhandled exception occurred while processing the request. 
        ServiceException: Code: InvalidAuthenticationToken Message: Access token has expired or is not yet valid. Inner error: AdditionalData: date: 2022-02-21T17:37:46 request-id: [removed] client-request-id: [removed] ClientRequestld: [removed] Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken) 
        Routing 

CodePudding user response:

The access token have a short lifetime, sometimes like an hour or even shorter. So you need to use a refresh token to ask AzureAd for a new access token when the current one is about to expire.

see this link https://docs.microsoft.com/en-us/azure/active-directory/develop/refresh-tokens

  • Related