Last active
June 13, 2022 22:42
-
-
Save Vaccano/cf0651e6f36a4650e8118ea3262c7f4a to your computer and use it in GitHub Desktop.
Attempt to get Azure AD working with Swagger
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.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.AddAuthorization(); | |
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 | |
{ | |
Type = SecuritySchemeType.OpenIdConnect, | |
Flows = new OpenApiOAuthFlows | |
{ | |
Implicit = 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. | |
var clientId = builder.Configuration.GetSection("AzureAd")["ClientId"]; | |
var clientSecret = builder.Configuration.GetSection("AzureAd")["ClientSecret"]; | |
app.UseSwagger(); | |
app.UseSwaggerUI(swaggerUiOptions => | |
{ | |
swaggerUiOptions.OAuthAppName("App Test"); | |
swaggerUiOptions.OAuthClientId(clientId); | |
swaggerUiOptions.OAuthClientSecret(clientSecret); | |
swaggerUiOptions.OAuthUseBasicAuthenticationWithAccessCodeGrant(); | |
}); | |
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