I am trying to setup Auth on a new minimal API. The API needs to connect out to Graph API (using GraphServiceClient) which I have working.
I need to get security working for the API. I need to setup SwaggerUI and then look at how the client (a sharepoint client) will call the API.
I've been trying to get Swagger UI setup and when I run Swagger and click on Authorize, it opens up a second browser tab and it resolves to a redirect endpoint and just sits there spinning (status of Pending).
`oAuth2 (OAuth2, authorizationCode with PKCE) OAuth2.0 Auth Code
Authorization URL: https://login.microsoftonline.com//oauth2/v2.0/authorize
Token URL: https://login.microsoftonline.com//oauth2/v2.0/token
Flow: authorizationCode with PKCE`
I am passing the client id and secret and selecting a scope.
It redirects and I just see this
I have the following when setting up Swagger
services.ApiRequireAuthentication()
.AddScoped<IUserContext, JwtUserContext>()
.AddAuthorization(options =>
{
options.AddPolicy(RoleNames.ApiAdminRole, policy =>
{
policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
policy.RequireRole("ApiAdmin");
});
options.AddPolicy(RoleNames.ApiAccessRole, policy =>
{
policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
policy.RequireRole("ApiAccess");
});
});
var apiScope = azureAd?.Scopes?.Api;
if (apiScope is null || string.IsNullOrEmpty(apiScope.Scope) || string.IsNullOrEmpty(apiScope.Description))
{
throw new ArgumentException("API Scope is not defined in the config.");
}
var authorizationUrl = $"https://login.microsoftonline.com/{azureAd?.TenantId}/oauth2/v2.0/authorize";
var tokenUrl = $"https://login.microsoftonline.com/{azureAd?.TenantId}/oauth2/v2.0/token";
services.AddEndpointsApiExplorer()
.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "SA DPC M365 API", Version = "v1" });
c.AddSecurityDefinition("oAuth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Description = $"OAuth2.0 Auth Code",
Name = "oAuth2",
In = ParameterLocation.Header,
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri(authorizationUrl),
TokenUrl = new Uri(tokenUrl),
Scopes = new Dictionary<string, string>()
{
{ apiScope.Scope, apiScope.Description }
}
}
}
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "oauth2"
},
Scheme = "oauth2",
Name = "oAuth2",
In = ParameterLocation.Header
},
new [] { apiScope.Scope }
}
});
});
}
The UI definition is
app.UseSwagger();
app.UseSwaggerUI(options =>
{
var azureSettings = configuration.GetAzureSettings();
options.EnableTryItOutByDefault();
options.OAuthClientId(azureSettings.ClientId);
options.OAuthClientSecret(azureSettings?.Credentials?.ClientSecre t);
options.OAuthUsePkce();
options.OAuthScopeSeparator(" ");
});
