27
loading...
This website collects cookies to deliver better user experience
public void ConfigureServices(IServiceCollection services)
{
services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "VolcanoAPI", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "YouAPI v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Startup.cs
with the necessary code. In the ConfigureServices()
method, add the following code:services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "swaggerAADdemo", Version = "v1" });
c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "OAuth2.0 Auth Code with PKCE",
Name = "oauth2",
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri(Configuration["AuthorizationUrl"]),
TokenUrl = new Uri(Configuration["TokenUrl"]),
Scopes = new Dictionary<string, string>
{
{ Configuration["ApiScope"], "read the api" }
}
}
}
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
},
new[] { Configuration["ApiScope"] }
}
});
});
Configure()
method to wire up the UI with the appropriate authentication settings. This bit will enable users to login in the UI before making API calls in the OpenAPI page.if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "swaggerAADdemo v1");
c.OAuthClientId(Configuration["OpenIdClientId"]);
c.OAuthUsePkce();
c.OAuthScopeSeparator(" ");
});
}
appsettings.json
file and add the following json at the end:"AuthorizationUrl":"https://login.microsoftonline.com/<your tenant Id>/oauth2/v2.0/authorize",
TokenUrl":"https://login.microsoftonline.com/<your tenant Id>/oauth2/v2.0/token",
"ApiScope": <your api scope(s)>,
"OpenIdClientId": "<your swagger app reg client id>"
APIScope
property should have a value similar to this "api://cd28264c-2a31-49df-b416-bf6f332c716d/". This is the scope expected in the Access token by your API. OpenIdClientId
should contain the Client ID from the Azure AD App Registration -> We did this as part of step 1 when we created the Azure AD App Registrations.