Created
June 17, 2022 18:50
-
-
Save Vaccano/5970963a66e4450cf10add1053292e9c to your computer and use it in GitHub Desktop.
Trying to Get Swagger Identity Working
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Authentication; | |
using Microsoft.AspNetCore.Authentication.JwtBearer; | |
using Microsoft.Identity.Web; | |
using Microsoft.OpenApi.Models; | |
var builder = WebApplication.CreateBuilder(args); | |
// Add services to the container. | |
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) | |
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd")).EnableTokenAcquisitionToCallDownstreamApi() | |
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph")) | |
.AddDownstreamWebApi("DownstreamApi",builder.Configuration.GetSection("DownstreamApi")) | |
.AddInMemoryTokenCaches(); | |
builder.Services.AddControllers(); | |
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle | |
builder.Services.AddEndpointsApiExplorer(); | |
var tenantId = builder.Configuration.GetSection("AzureAd")["TenantId"]; | |
builder.Services.AddSwaggerGen(options => | |
{ | |
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme | |
{ | |
// This next line is what is causing the issue | |
Type = SecuritySchemeType.OpenIdConnect, | |
Flows = new OpenApiOAuthFlows | |
{ | |
AuthorizationCode = new OpenApiOAuthFlow | |
{ | |
AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize"), | |
TokenUrl = new Uri($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token"), | |
Scopes = new Dictionary<string, string> { { "openid", "Scope to enable OIDC" } } | |
} | |
} | |
}); | |
}); | |
var app = builder.Build(); | |
// Configure the HTTP request pipeline. | |
if (app.Environment.IsDevelopment()) | |
{ | |
app.UseSwagger(); | |
var clientId = builder.Configuration.GetSection("AzureAd")["ClientId"]; | |
var clientSecret = builder.Configuration.GetSection("AzureAd")["ClientSecret"]; | |
app.UseSwaggerUI(swaggerUiOptions => | |
{ | |
swaggerUiOptions.OAuthAppName("Framework App Test"); | |
swaggerUiOptions.OAuthClientId(clientId); | |
swaggerUiOptions.OAuthClientSecret(clientSecret); | |
swaggerUiOptions.OAuthUsePkce(); | |
swaggerUiOptions.OAuthUseBasicAuthenticationWithAccessCodeGrant(); | |
// Check the openid scope by default. (It adds in user information and is almost always wanted.) | |
swaggerUiOptions.OAuthScopes("openid"); | |
}); | |
} | |
app.UseHttpsRedirection(); | |
app.UseAuthentication(); | |
app.UseAuthorization(); | |
app.MapControllers(); | |
app.Run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment