title: Unable to call Graph API in .net core
body: <p>net core application. I am trying to call Graph API in my application. Below is my code. This is the policy I  applied on top of Controller. </p>
  
  <pre><code>[Authorize(Policy = "APGroupsOnly")] 
  </code></pre>
  
  <p>Below policy I added in startup.</p>
  
  <pre><code>services.AddAuthorization(options =&gt;
  {
      options.AddPolicy("APGroupsOnly", policy =&gt;
             policy.Requirements.Add(new GroupsCheckRequirement("YourGroupID")));
  });
  </code></pre>
  
  <p>I am trying to hit apis from swagger. Below is my swagger config.</p>
  
  <pre><code>"ClientId": "my client id",
  "ClientSecret": "my client secrete",
  "AuthorizationUrl": "https://login.microsoftonline.com/myid/oauth2/authorize",
  "TokenUrl": "https://login.microsoftonline.com/myid/oauth2/token"
  </code></pre>
  
  <p>Below is my MSGraphService.cs</p>
  
  <pre><code>public async Task&lt;User&gt; GetMeAsync(string accessToken)
  {
      User currentUserObject;
  
      try
      {
          PrepareAuthenticatedClient(accessToken);
          currentUserObject = await graphServiceClient.Me.Request().GetAsync();
       }
       catch (ServiceException e)
       {
           Debug.WriteLine("We could not fetch details of the currently signed-in user: " + $"{e}");
           return null;
       }
  
      return currentUserObject;
  }
  
  private void PrepareAuthenticatedClient(string accessToken)
  {
      if (graphServiceClient == null)
      {
          // Create Microsoft Graph client.
          try
          {
              graphServiceClient = new GraphServiceClient("https://graph.microsoft.com/.default",
                  new DelegateAuthenticationProvider(
                      async (requestMessage) =&gt;
                      {
                          await Task.Run(() =&gt;
                          {
                              requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                          });
                      }));
          }
          catch (Exception ex)
          {
              Debug.WriteLine($"Could not create a graph client {ex}");
          }
      }
  }
  
  </code></pre>
  
  <p>Below is my GroupsCheckHandler</p>
  
  <pre><code>public class GroupsCheckHandler : AuthorizationHandler&lt;GroupsCheckRequirement&gt;
  {
      private IHttpContextAccessor _httpContextAccessor;
      private readonly IMSGraphService graphService;
      public GroupsCheckHandler(IHttpContextAccessor httpContextAccessor, IMSGraphService MSGraphService)
      {
          _httpContextAccessor = httpContextAccessor;
          this.graphService = MSGraphService;
      }
  
      protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, GroupsCheckRequirement requirement)
      {
          var accessToken = _httpContextAccessor.HttpContext.Request.Headers["Authorization"];
          User me = await graphService.GetMeAsync(accessToken);
      }
  }
  
  </code></pre>
  
  <p>Whenever I check execute, I get the following error.</p>
  
  <blockquote>
    <p>We could not fetch details of the currently signed-in user: Status Code: Unauthorized
        Microsoft.Graph.ServiceException: Code: InvalidAuthenticationToken
        Message: CompactToken parsing failed with error code: 80049217</p>
  </blockquote>
  
  <p>Below is my startup file.</p>
  
  <pre><code> public class Startup
      {
          public Startup(IConfiguration configuration)
          {
              Configuration = configuration;
              azureActiveDirectoryOptions = configuration.GetSection("AzureAd").Get&lt;AzureActiveDirectoryOptions&gt;();
              swaggerUIOptions = configuration.GetSection("Swagger").Get&lt;SwaggerUIOptions&gt;();
          }
  
          public IConfiguration Configuration { get; }
  
          private readonly AzureActiveDirectoryOptions azureActiveDirectoryOptions;
          private readonly SwaggerUIOptions swaggerUIOptions;
          //
          // This method gets called by the runtime. Use this method to add services to the container.
          public void ConfigureServices(IServiceCollection services)
          {
              services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
              services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();
              services.AddTransient&lt;IMSGraphService, MSGraphService&gt;();
              services
                 .AddAuthentication(o =&gt;
                 {
                     o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
  
                 })
                 .AddJwtBearer(o =&gt;
                 {
                     o.Authority = azureActiveDirectoryOptions.Authority;
  
                     o.TokenValidationParameters = new TokenValidationParameters
                     {
  
                         ValidAudiences = new List&lt;string&gt;
                         {
                            azureActiveDirectoryOptions.AppIdUri,
                            azureActiveDirectoryOptions.ClientId
                         },
                         ValidateIssuer = true,
                         ValidateAudience = true,
                         ValidIssuer = "https://myorg.onmicrosoft.com/oauth2/default",
                         RoleClaimType = ClaimTypes.Role
                     };
                 });
  
              services.AddMvc(options =&gt;
              {
  
                  var policy = new AuthorizationPolicyBuilder()
                      .RequireAuthenticatedUser()
                      .Build();
                  options.Filters.Add(new AuthorizeFilter(policy));
              }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); ;
  
              services.AddSwaggerGen(c =&gt;
              {
                  c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
  
                  c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                  {
                      Type = "oauth2",
                      Flow = "implicit",
                      AuthorizationUrl = swaggerUIOptions.AuthorizationUrl,
                      TokenUrl = swaggerUIOptions.TokenUrl,
                      Scopes = new Dictionary&lt;string, string&gt;
                      {
                          {"Read", "13469a45-a2ea-45a1-96e7-6580f57b6e30/.default" }
                      }
                  });
                  c.AddSecurityRequirement(new Dictionary&lt;string, IEnumerable&lt;string&gt;&gt;
                  {
                          { "oauth2", new[] { "readAccess", "writeAccess" } }
                  });
              });
  
              services.AddAuthorization(options =&gt;
              {
                  options.AddPolicy("APGroupsOnly", policy =&gt;
                         policy.Requirements.Add(new GroupsCheckRequirement("YourGroupID")));
              });
              services.AddScoped&lt;IAuthorizationHandler, GroupsCheckHandler&gt;();
          }
  
          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
          public void Configure(IApplicationBuilder app, IHostingEnvironment env)
          {
              if (env.IsDevelopment())
              {
                  app.UseDeveloperExceptionPage();
              }
              else
              {
                  app.UseHsts();
              }
              app.UseSwagger();
              app.UseSwaggerUI(c =&gt;
              {
                  c.RoutePrefix = "swagger";
                  c.OAuthClientId(swaggerUIOptions.ClientId);
                  c.OAuthClientSecret(swaggerUIOptions.ClientSecret);
                  c.OAuthRealm(azureActiveDirectoryOptions.ClientId);
                  c.OAuthAppName("Swagger");
                  c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                  c.OAuthAdditionalQueryStringParams(new Dictionary&lt;string, string&gt;() { { "resource", azureActiveDirectoryOptions.AppIdUri } });
              });
              app.UseAuthentication();
              app.UseHttpsRedirection();
              app.UseMvc();
          }
      }
  </code></pre>
  
  <p>Can someone help me to fix this issue? Any help would be appreciated. Thanks.</p>