Search code examples
asp.net-coremicrosoft-graph-apiasp.net-identity

GraphServiceClient throw an exception when AzureAD is not the default authentication scheme


In my ASP.NET Core application I've multiple authentication scheme.

GraphServiceClient throw IDW10503: Cannot determine the cloud Instance. The provided authentication scheme was '' exception if OpenIdConnect is not default scheme. I need 'cookie' as default scheme.

My configuration:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddNegotiate()
    .AddMicrosoftIdentityWebApp(builder.Configuration, configSectionName: "Authentication:AzureAD");

builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

My Page:

[Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)]
public class TestModel : PageModel
{
    public int UnreadMessages { get; set; }

    public async Task<IActionResult> OnGetAsync([FromServices] GraphServiceClient graph)
    {
        UnreadMessages = (await graph.Me.MailFolders["Inbox"].Messages
                                     .Request()
                                     .Filter("isRead ne true")
                                     .GetAsync()).Count;
        return Page();
    }
}

I can I configure GraphServiceClient to work? Thank you!


Solution

  • I've found a way to tell GraphServiceClient what authentication schema to use using WithAuthenticationScheme method:

    var messages = await graph.Me.MailFolders["Inbox"].Messages
        .Request()
        .WithAuthenticationScheme(OpenIdConnectDefaults.AuthenticationScheme)
        .Filter("isRead ne true")
        .GetAsync();