title: Microsoft.Graph.ServiceException' Code: BadRequest Message: Current authenticated context is not valid for this request
body: <p>I'm having trouble when using the Microsoft Graph API. Whenever I try to get a calendar, I get the following error message:</p>
  
  <blockquote>
    <p>Exception thrown: 'Microsoft.Graph.ServiceException' in
    System.Private.CoreLib.dll: 'Code: BadRequest Message: Current
    authenticated context is not valid for this request</p>
  </blockquote>
  
  <p>At first, I thought it was similar to <a href="https://stackoverflow.com/questions/42090125/microsoft-graph-current-authenticated-context-is-not-valid-for-this-request">this</a> post, but my user is authenticated, so I believe it's not the case.</p>
  
  <p>Here's my code:</p>
  
  <p><code>EventController.cs</code></p>
  
  <pre class="lang-cs prettyprint-override"><code>public async Task&lt;Calendar&gt; GetEventInfoAsync()
      {
          var accessToken = await getAcessTokenAsync();
          DelegateAuthenticationProvider delegateAuthenticationProvider = new DelegateAuthenticationProvider(
              (requestMessage) =&gt; 
              {
                  requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                  return Task.FromResult(0);
              }
          );
          GraphServiceClient graphClient = new GraphServiceClient(delegateAuthenticationProvider);
          var calendar = await graphClient.Me.Calendar.Request().GetAsync();
          return calendar;
      }
  </code></pre>
  
  <p>And this is how I get the access token: </p>
  
  <pre class="lang-cs prettyprint-override"><code>public async Task&lt;string&gt; getAcessTokenAsync()
      {
          if(User.Identity.IsAuthenticated)
          {
              var userId = User.FindFirst("MicrosoftUserId")?.Value;
              ConfidentialClientApplication cca =
                  new ConfidentialClientApplication( Configuration["MicrosoftAuth:ClientId"],
                                                      String.Format(System.Globalization.CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}{1}", "common", "/v2.0"),
                                                      Configuration["MicrosoftAuth:RedirectUri"]+ "signin-oidc", 
                                                      new Microsoft.Identity.Client.ClientCredential(Configuration["MicrosoftAuth:ClientSecret"]),
                                                      new SessionTokenCache(userId,_memoryCache).GetCacheInstance(),
                                                      null);               
              var token = await cca.AcquireTokenForClientAsync(new string[]{"https://graph.microsoft.com/.default"});
              return token.AccessToken;
          }
          else
              throw new Exception("User is not autenticated");
      }
  </code></pre>
  
  <p>Finally, this is how the authentication options look in the startup file.</p>
  
  <pre><code>services.AddAuthentication().AddOpenIdConnect(openIdOptions =&gt; 
          {
              openIdOptions.ResponseType = OpenIdConnectResponseType.CodeIdToken;
              openIdOptions.Authority = String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}{1}", "common", "/v2.0");
              openIdOptions.ClientId = Configuration["MicrosoftAuth:ClientId"];
              openIdOptions.ClientSecret = Configuration["MicrosoftAuth:ClientSecret"];
              openIdOptions.SaveTokens = true;
              openIdOptions.TokenValidationParameters = new TokenValidationParameters{
                  ValidateIssuer = false
              };
              var scopes = Configuration["MicrosoftAuth:Scopes"].Split(' ');
                  foreach (string scope in scopes){
                      openIdOptions.Scope.Add(scope);
              }
              openIdOptions.Events = new OpenIdConnectEvents{
                  OnAuthorizationCodeReceived = async (context) =&gt;
                  {   
                      var userId = context.Principal.Claims.First(item =&gt; item.Type == ObjectIdentifierType).Value;
                      IMemoryCache memoryCache = context.HttpContext.RequestServices.GetRequiredService&lt;IMemoryCache&gt;();
                      ConfidentialClientApplication cca =
                          new ConfidentialClientApplication( Configuration["MicrosoftAuth:ClientId"],
                                                              String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}{1}{2}", "common", "/v2.0", "/adminconsent"),
                                                              Configuration["MicrosoftAuth:RedirectUri"]+ "signin-oidc", 
                                                              new Microsoft.Identity.Client.ClientCredential(Configuration["MicrosoftAuth:ClientSecret"]),
                                                              new SessionTokenCache(userId,memoryCache).GetCacheInstance(),
                                                              null);
                      var code = context.ProtocolMessage.Code;                        
                      var result = await cca.AcquireTokenByAuthorizationCodeAsync(code,new string[]{"User.Read.All", "Calendars.ReadWrite"});
                      context.HandleCodeRedemption(result.AccessToken, result.IdToken);
                  },
              };
          });
  </code></pre>
  
  <p>My app is registered in the Microsoft Application Registration Portal, and I do get a token when I request for it, so I'm not sure what could possibly be causing the problem. </p>