-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
AspNetCore: Hide swagger from nonauthorized users #1604
Labels
Comments
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: domaindrivendev/Swashbuckle.WebApi#601)
The text was updated successfully, but these errors were encountered: