Can't Login with Swagger to Azure Active Directory with new ASP.NET Core 8 app

475 Views Asked by At

I started a new ASP.NET Core 8 site with the Azure identity template and can't login through the Swagger UI to make web requests.

When I run and enter my client id for the app created on Azure I get the error:

We're unable to complete your request
invalid_request: The provided value for the input parameter 'redirect_uri' is not valid. The expected value is a URI which matches a redirect URI registered for this client application.

I'm having a hard time finding the exact docs that mention how to configure this, but based on the error above, what do I need to look at configuring?

My appsettings.json looks like this:

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "foo.onmicrosoft.com",
    "TenantId": "tenant-id-from-app-registrations-in-azure",
    "ClientId": "client-id-from-my-app-in-azure",
    "CallbackPath": "/signin-oidc",
    "Scopes": "access_as_user"
}

enter image description here

And my startup code looks like this:

   public static void Main(string[] args)
   {
       var builder = WebApplication.CreateBuilder(args);

       // Add services to the container.
       builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
           .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

       builder.Services.AddControllers();
       // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
       builder.Services.AddEndpointsApiExplorer();
       builder.Services.AddSwaggerGen(
           c =>
           {
               c.SwaggerDoc("v1", new OpenApiInfo
               {
                   Title = "Commerce.API",
                   Version = "v1",
               });
               c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
               {
                   Type = SecuritySchemeType.OAuth2,
                   Flows = new OpenApiOAuthFlows
                   {
                       Implicit = new OpenApiOAuthFlow()
                       {
                           AuthorizationUrl = new Uri("https://login.microsoftonline.com/common/oauth2/v2.0/authorize"),
                           TokenUrl = new Uri("https://login.microsoftonline.com/common/common/v2.0/token"),
                           Scopes = new Dictionary<string, string> { { "access_as_user", "thescopelul" } }
                       }
                   }
               });
               c.AddSecurityRequirement(new OpenApiSecurityRequirement() {
               {
                   new OpenApiSecurityScheme {
                       Reference = new OpenApiReference {
                           Type = ReferenceType.SecurityScheme,
                           Id = "oauth2"
                       },
                       Scheme = "oauth2",
                       Name = "oauth2",
                       In = ParameterLocation.Header
                   },
                   new List <string> ()
                   }
               });
           });

       var app = builder.Build();

       // Configure the HTTP request pipeline.
       if (app.Environment.IsDevelopment())
       {
           app.UseSwagger();
           app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Commerce.API v1"));
       }

       app.UseHttpsRedirection();

       app.UseAuthentication();

       app.UseAuthorization();


       app.MapControllers();

       app.Run();
   }

Redirect URI's: enter image description here

1

There are 1 best solutions below

0
On

You need to specify redirect_uri when calling .AddMicrosoftIdentityWebApp(). However you will need to do more manual configuration instead of nice and smooth passing of builder.Configuration.GetSection("AzureAd") or maybe I am not aware of some overload of this method. Anyway, try following:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddMicrosoftIdentityWebApi(identity =>
                    {
                        identity.ClientId = "clientId";
                        identity.TenantId = "tenantId";

                        // and so on, and so on with the rest of your config
                        // important code below:

                        identity.Events = new OpenIdConnectEvents {
                            OnRedirectToIdentityProvider = async ctx =>
                            {
                                ctx.ProtocolMessage.RedirectUri = "Your redirect uri"
                                await Task.Yield();
                            }
                        };

}, openIdConnectScheme: OpenIdConnectDefaults.AuthenticationScheme);