Skip to content

Instantly share code, notes, and snippets.

@wallymathieu
Last active March 28, 2019 13:21
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wallymathieu/e149735645232dfc0dd92f8e6fc71f9b to your computer and use it in GitHub Desktop.
Save wallymathieu/e149735645232dfc0dd92f8e6fc71f9b to your computer and use it in GitHub Desktop.
HowTo register auth for swashbuckle with identity server on asp.net core
Namespace ProjectWithSwagger
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
//....
services.ConfigureSwaggerGen(swaggerGen =>
{
swaggerGen.AddSecurityDefinition("Swagger", new OAuth2Scheme
{
AuthorizationUrl = UriCreate(Configuration.IdentityServerSettings.Authority, "/connect/authorize").ToString(),
Flow = "implicit",
TokenUrl = UriCreate(Configuration.IdentityServerSettings.Authority, "/connect/token").ToString(),
Scopes = { { "api.name", "The Scope needed to access API" } }
});
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
IAppointmentPlusService aps, IMigrationsHandler mh)
{
app.UseSwagger(c =>
{
c.RouteTemplate = "swagger/{documentName}/swagger.json";
});
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUi(c =>
{
c.ConfigureOAuth2("api.name.swagger", SwaggerSecret, "swagger-ui-realm", "API Swagger UI");
});
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = Configuration.IdentityServerSettings.Authority,
RequireHttpsMetadata = !_env.IsDevelopment(),
ApiName = "api.name",
SupportedTokens = SupportedTokens.Both
});
}
}
@zuckerthoben
Copy link

How would you do this if you want to access Azure Ad via Identity Server? I have the issue that either the Identity Server redirect is sending something weird back to the Swagger UI or the Swagger UI is not accepting the IdentityServer token.

@FrankV01
Copy link

FrankV01 commented Jan 26, 2018

The UseIdentityServerAuthentication extension method comes from IdentityServer4? I don't know if this is ever mentioned but I just thought I'd throw a confirmation out there. I guess what I mean (to be more specific), is which NuGet packages are you dependent on here?

@wallymathieu
Copy link
Author

I think this example might be a bit dated. It's probably Swashbuckle.AspNetCore and
IdentityServer4.AccessTokenValidation. I think that it might have become a bit easier to configure with later versions of Swashbuckle.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment