Created
September 17, 2020 05:22
-
-
Save lurumad/249d7fb47197fd5990f31320455ee2dc to your computer and use it in GitHub Desktop.
Add authentication to SwaggerUI
This file contains hidden or 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 System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Authentication; | |
using Microsoft.AspNetCore.Authentication.Cookies; | |
using Microsoft.AspNetCore.Authentication.OpenIdConnect; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.HttpsPolicy; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Hosting; | |
using Microsoft.Extensions.Logging; | |
namespace SwashbuckleAuthentication | |
{ | |
public class Startup | |
{ | |
public Startup(IConfiguration configuration) | |
{ | |
Configuration = configuration; | |
} | |
public IConfiguration Configuration { get; } | |
// This method gets called by the runtime. Use this method to add services to the container. | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
services | |
.AddAuthentication(options => | |
{ | |
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; | |
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; | |
}) | |
.AddCookie() | |
.AddOpenIdConnect(options => | |
{ | |
options.Authority = "https://demo.identityserver.io"; | |
options.ClientId = "interactive.confidential"; | |
options.ClientSecret = "secret"; | |
options.ResponseType = "code"; | |
options.SaveTokens = true; | |
}) | |
.Services | |
.AddSwaggerGen() | |
.AddControllers(); | |
} | |
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. | |
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |
{ | |
if (env.IsDevelopment()) | |
{ | |
app.UseDeveloperExceptionPage(); | |
} | |
app.UseAuthentication(); | |
app.Use(async (context, next) => | |
{ | |
if (context.Request.Path.StartsWithSegments("/swagger", StringComparison.OrdinalIgnoreCase) | |
&& !context.User.Identity.IsAuthenticated) | |
{ | |
await context.ChallengeAsync(); | |
return; | |
} | |
await next(); | |
}); | |
app.UseSwagger(); | |
app.UseSwaggerUI(setup => setup.SwaggerEndpoint("/swagger/v1/swagger.json", "v1.0")); | |
app.UseHttpsRedirection(); | |
app.UseRouting(); | |
app.UseAuthorization(); | |
app.UseEndpoints(endpoints => | |
{ | |
endpoints.MapControllers(); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment