Skip to content

Instantly share code, notes, and snippets.

@Vaccano
Last active June 13, 2022 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vaccano/cf0651e6f36a4650e8118ea3262c7f4a to your computer and use it in GitHub Desktop.
Save Vaccano/cf0651e6f36a4650e8118ea3262c7f4a to your computer and use it in GitHub Desktop.
Attempt to get Azure AD working with Swagger
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