Hi, I use Nswag in my company and I want to allow access to swagger only with login
(it is private API so other users out of company should not have access).
Is that possible?
Currently I use NSwag.AspNetCore nuget.
(Related: https://github.com/domaindrivendev/Swashbuckle/issues/601)
This feature is not built-in and is probably handled best with an own middleware or proxy in front of the web app
I just had this isse, asked Rico, which redirected me here.
I implemented the middleware as sad before, in an extension class:
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using System;
/// <summary>
/// The extension methods that extends <see cref="IApplicationBuilder" /> for authentication purposes
/// </summary>
public static class ApplicationBuilderExtensions
{
/// <summary>
/// Requires authentication for paths that starts with <paramref name="pathPrefix" />
/// </summary>
/// <param name="app">The application builder</param>
/// <param name="pathPrefix">The path prefix</param>
/// <returns>The application builder</returns>
public static IApplicationBuilder RequireAuthenticationOn(this IApplicationBuilder app, string pathPrefix)
{
return app.Use((context, next) =>
{
// First check if the current path is the swagger path
if (context.Request.Path.HasValue && context.Request.Path.Value.StartsWith(pathPrefix, StringComparison.InvariantCultureIgnoreCase))
{
// Secondly check if the current user is authenticated
if (!context.User.Identity.IsAuthenticated)
{
return context.ChallengeAsync();
}
}
return next();
});
}
}
This will redirect the user to the login page if you have properly set up the authentication mecanism.
Then, when building your app
app.RequireAuthenticationOn("/swagger");
//Enable Swagger + Swagger Ui
app.UseSwaggerUi3WithApiExplorer(this.ConfigureSwagger);
Most helpful comment
I just had this isse, asked Rico, which redirected me here.
I implemented the middleware as sad before, in an extension class:
This will redirect the user to the login page if you have properly set up the authentication mecanism.
Then, when building your app