swagger hide endpoints on specific user

Im trying to hide which endpoints are shown in swagger depending on which users are logged in. This is not working and i don’t understand why. Im using microsoft identity and swashbuckle In the HideEndpointsBasedOnUserFilter class the code is hitting the “if (!isUserInRole)” and goes into this but the commands inside are not removing the swagger endbpoint . Here is my code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[SwaggerHide("Admin")]
[HttpGet]
[Route("cabinetGatewaySvc/accesscontrol/{clientId}/{cardId}")]
public async Task<ActionResult<string>> AccessControl(string clientId, string cardId)
{
_twoTraceLogger.LogTrace("CabinetController gets called");
var result = await _canOpenPort.ValidateWearerAsync(clientId, cardId);
return Ok(result);
}
namespace MsCabinetGateway.SwaggerConfig
{
public class SwaggerHideAttribute : Attribute
{
public string RequiredRole { get; set; }
public SwaggerHideAttribute(string requiredRole)
{
RequiredRole = requiredRole;
}
}
}
public class HideEndpointsBasedOnUserFilter : IOperationFilter
{
private readonly IHttpContextAccessor _httpContextAccessor;
public HideEndpointsBasedOnUserFilter(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var user = _httpContextAccessor.HttpContext?.User;
if (user == null || !user.Identity.IsAuthenticated)
{
return; // No authenticated user, skip filtering
}
// Check if the action has the SwaggerHideAttribute
var hideAttribute = context.MethodInfo.GetCustomAttribute<SwaggerHideAttribute
();
if (hideAttribute != null)
{
var requiredRole = hideAttribute.RequiredRole;
var isUserInRole = user.IsInRole(requiredRole);
// Log the roles and required role
Console.WriteLine($"Required role: {requiredRole}, Is user in role:
{isUserInRole}");
// If the user doesn't have the required role, hide the endpoint
if (!isUserInRole)
{
operation.Tags.Clear(); // Hide operation by removing tags
operation.Summary = null; // Optionally clear the summary
operation.Description = null; // Optionally clear the description
operation.Responses.Clear(); // Optionally clear responses
}
}
}
}
}
public class Program
{
private static AppSettings? ApplicationSettings { get; set; }
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var connectionString =
builder.Configuration.GetConnectionString("MsCabinetGatewayContextConnection") ??
throw
new InvalidOperationException("Connection string
'MsCabinetGatewayContextConnection'
not
found.");
builder.Services.AddDbContext<MsCabinetGatewayContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddHttpContextAccessor();
builder.Services.AddDefaultIdentity<Areas.Identity.Data.MsCabinetGatewayUser>
(options => options.SignIn.RequireConfirmedAccount =
true).AddEntityFrameworkStores<MsCabinetGatewayContext>();
IConfiguration configuration = builder.Configuration;
ApplicationSettings = new AppSettings();
configuration.Bind(ApplicationSettings);
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at
https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Cabinet gateway",
Version = "v1",
Description = "Cabinet gateway documentation."
});
c.OperationFilter<HideEndpointsBasedOnUserFilter>();
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
c.EnableAnnotations();
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description =
Adapters.RestApiAdapter.Constants.RestProperties.Description,
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
builder.Services.AddHttpContextAccessor();
});
builder.Services.AddCustomConfiguration(configuration);
if (ApplicationSettings.AppInsightConfig is null)
{
ApplicationSettings.AppInsightConfig = new();
ApplicationSettings.AppInsightConfig.InstrumentationKey =
configuration.GetSection("ApplicationInsights").GetSection("InstrumentationKey").Value;
ApplicationSettings.AppInsightConfig.ConnectionString =
configuration.GetSection("ApplicationInsights").GetSection("ConnectionString").Value;
}
builder.Services.AddServiceDependencies(ApplicationSettings);
//builder.WebHost.ConfigureKestrel((context, serverOptions) =>
//{
// serverOptions.Listen(IPAddress.Any, 5000);
//});
builder.Services.AddLogging(builder =>
{
// Only Application Insights is registered as a logger provider
builder.AddApplicationInsights(
configureTelemetryConfiguration:
(config) => config.ConnectionString =
configuration["ApplicationInsights:ConnectionString"],
configureApplicationInsightsLoggerOptions: (options) => { }
);
});
var app = builder.Build();
GrpcAdapterExtention.AddServiceConfigurations(app);
//app.Use(async (context, next) =>
//{
// if (context.Request.Path.StartsWithSegments("/swagger")
// && !context.User.Identity.IsAuthenticated)
// {
// context.Response.Redirect("/Identity/Account/Login");
// return;
// }
// await next();
//});
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.UseStaticFiles();
app.UseSwagger();
app.UseSwaggerUI();
app.UseSwagger(c =>
{
c.RouteTemplate = "cabinetGatewaySvc/swagger/{documentname}/swagger.json";
});
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/cabinetGatewaySvc/swagger/v1/swagger.json", "Cabinet
Gateway Microservice");
c.RoutePrefix = "cabinetGatewaySvc/swagger";
});
app.UseRouting();
app.UseEndpoints(endpoints =>
{
_ = endpoints.MapControllers();
});
app.Run();
}
}
</code>
<code>[SwaggerHide("Admin")] [HttpGet] [Route("cabinetGatewaySvc/accesscontrol/{clientId}/{cardId}")] public async Task<ActionResult<string>> AccessControl(string clientId, string cardId) { _twoTraceLogger.LogTrace("CabinetController gets called"); var result = await _canOpenPort.ValidateWearerAsync(clientId, cardId); return Ok(result); } namespace MsCabinetGateway.SwaggerConfig { public class SwaggerHideAttribute : Attribute { public string RequiredRole { get; set; } public SwaggerHideAttribute(string requiredRole) { RequiredRole = requiredRole; } } } public class HideEndpointsBasedOnUserFilter : IOperationFilter { private readonly IHttpContextAccessor _httpContextAccessor; public HideEndpointsBasedOnUserFilter(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } public void Apply(OpenApiOperation operation, OperationFilterContext context) { var user = _httpContextAccessor.HttpContext?.User; if (user == null || !user.Identity.IsAuthenticated) { return; // No authenticated user, skip filtering } // Check if the action has the SwaggerHideAttribute var hideAttribute = context.MethodInfo.GetCustomAttribute<SwaggerHideAttribute (); if (hideAttribute != null) { var requiredRole = hideAttribute.RequiredRole; var isUserInRole = user.IsInRole(requiredRole); // Log the roles and required role Console.WriteLine($"Required role: {requiredRole}, Is user in role: {isUserInRole}"); // If the user doesn't have the required role, hide the endpoint if (!isUserInRole) { operation.Tags.Clear(); // Hide operation by removing tags operation.Summary = null; // Optionally clear the summary operation.Description = null; // Optionally clear the description operation.Responses.Clear(); // Optionally clear responses } } } } } public class Program { private static AppSettings? ApplicationSettings { get; set; } public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); var connectionString = builder.Configuration.GetConnectionString("MsCabinetGatewayContextConnection") ?? throw new InvalidOperationException("Connection string 'MsCabinetGatewayContextConnection' not found."); builder.Services.AddDbContext<MsCabinetGatewayContext>(options => options.UseSqlServer(connectionString)); builder.Services.AddHttpContextAccessor(); builder.Services.AddDefaultIdentity<Areas.Identity.Data.MsCabinetGatewayUser> (options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<MsCabinetGatewayContext>(); IConfiguration configuration = builder.Configuration; ApplicationSettings = new AppSettings(); configuration.Bind(ApplicationSettings); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Cabinet gateway", Version = "v1", Description = "Cabinet gateway documentation." }); c.OperationFilter<HideEndpointsBasedOnUserFilter>(); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); c.EnableAnnotations(); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { Name = "Authorization", Type = SecuritySchemeType.ApiKey, Scheme = "Bearer", BearerFormat = "JWT", In = ParameterLocation.Header, Description = Adapters.RestApiAdapter.Constants.RestProperties.Description, }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new string[] {} } }); builder.Services.AddHttpContextAccessor(); }); builder.Services.AddCustomConfiguration(configuration); if (ApplicationSettings.AppInsightConfig is null) { ApplicationSettings.AppInsightConfig = new(); ApplicationSettings.AppInsightConfig.InstrumentationKey = configuration.GetSection("ApplicationInsights").GetSection("InstrumentationKey").Value; ApplicationSettings.AppInsightConfig.ConnectionString = configuration.GetSection("ApplicationInsights").GetSection("ConnectionString").Value; } builder.Services.AddServiceDependencies(ApplicationSettings); //builder.WebHost.ConfigureKestrel((context, serverOptions) => //{ // serverOptions.Listen(IPAddress.Any, 5000); //}); builder.Services.AddLogging(builder => { // Only Application Insights is registered as a logger provider builder.AddApplicationInsights( configureTelemetryConfiguration: (config) => config.ConnectionString = configuration["ApplicationInsights:ConnectionString"], configureApplicationInsightsLoggerOptions: (options) => { } ); }); var app = builder.Build(); GrpcAdapterExtention.AddServiceConfigurations(app); //app.Use(async (context, next) => //{ // if (context.Request.Path.StartsWithSegments("/swagger") // && !context.User.Identity.IsAuthenticated) // { // context.Response.Redirect("/Identity/Account/Login"); // return; // } // await next(); //}); app.UseAuthentication(); app.UseAuthorization(); app.MapRazorPages(); app.UseStaticFiles(); app.UseSwagger(); app.UseSwaggerUI(); app.UseSwagger(c => { c.RouteTemplate = "cabinetGatewaySvc/swagger/{documentname}/swagger.json"; }); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/cabinetGatewaySvc/swagger/v1/swagger.json", "Cabinet Gateway Microservice"); c.RoutePrefix = "cabinetGatewaySvc/swagger"; }); app.UseRouting(); app.UseEndpoints(endpoints => { _ = endpoints.MapControllers(); }); app.Run(); } } </code>
[SwaggerHide("Admin")]
[HttpGet]
[Route("cabinetGatewaySvc/accesscontrol/{clientId}/{cardId}")]
public async Task<ActionResult<string>> AccessControl(string clientId, string cardId)
{
_twoTraceLogger.LogTrace("CabinetController gets called");
var result = await _canOpenPort.ValidateWearerAsync(clientId, cardId);
return Ok(result);
}


namespace MsCabinetGateway.SwaggerConfig
{
public class SwaggerHideAttribute : Attribute
{
    public string RequiredRole { get; set; }

    public SwaggerHideAttribute(string requiredRole)
    {
        RequiredRole = requiredRole;
    }
}
}

public class HideEndpointsBasedOnUserFilter : IOperationFilter
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public HideEndpointsBasedOnUserFilter(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var user = _httpContextAccessor.HttpContext?.User;

        if (user == null || !user.Identity.IsAuthenticated)
        {
            return; // No authenticated user, skip filtering
        }

        // Check if the action has the SwaggerHideAttribute
        var hideAttribute = context.MethodInfo.GetCustomAttribute<SwaggerHideAttribute 
        ();
        if (hideAttribute != null)
        {
            var requiredRole = hideAttribute.RequiredRole;
            var isUserInRole = user.IsInRole(requiredRole);

            // Log the roles and required role
            Console.WriteLine($"Required role: {requiredRole}, Is user in role: 
            {isUserInRole}");

            // If the user doesn't have the required role, hide the endpoint
            if (!isUserInRole)
            {
               
                operation.Tags.Clear(); // Hide operation by removing tags
                operation.Summary = null; // Optionally clear the summary
                operation.Description = null; // Optionally clear the description
                operation.Responses.Clear(); // Optionally clear responses
                
            }
        }
    }



}
}

 public class Program
 {
 private static AppSettings? ApplicationSettings { get; set; }
 public static void Main(string[] args)
 {
     var builder = WebApplication.CreateBuilder(args);
     var connectionString = 
     builder.Configuration.GetConnectionString("MsCabinetGatewayContextConnection") ?? 
     throw 
     new InvalidOperationException("Connection string 
    'MsCabinetGatewayContextConnection' 
    not 
    found.");

     builder.Services.AddDbContext<MsCabinetGatewayContext>(options => 
     options.UseSqlServer(connectionString));
     builder.Services.AddHttpContextAccessor();
     builder.Services.AddDefaultIdentity<Areas.Identity.Data.MsCabinetGatewayUser> 
     (options => options.SignIn.RequireConfirmedAccount = 
     true).AddEntityFrameworkStores<MsCabinetGatewayContext>();
     IConfiguration configuration = builder.Configuration;
     ApplicationSettings = new AppSettings();
     configuration.Bind(ApplicationSettings);

     builder.Services.AddControllers();
     // Learn more about configuring Swagger/OpenAPI at 
     https://aka.ms/aspnetcore/swashbuckle
     builder.Services.AddEndpointsApiExplorer();
     builder.Services.AddSwaggerGen(c => {
         c.SwaggerDoc("v1", new OpenApiInfo
         {
             Title = "Cabinet gateway",
             Version = "v1",
             Description = "Cabinet gateway documentation."
         });

         c.OperationFilter<HideEndpointsBasedOnUserFilter>();

         // Set the comments path for the Swagger JSON and UI.
         var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
         var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
         c.IncludeXmlComments(xmlPath);

         c.EnableAnnotations();
         c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
         {
             Name = "Authorization",
             Type = SecuritySchemeType.ApiKey,
             Scheme = "Bearer",
             BearerFormat = "JWT",
             In = ParameterLocation.Header,
             Description = 
          Adapters.RestApiAdapter.Constants.RestProperties.Description,
         });
         c.AddSecurityRequirement(new OpenApiSecurityRequirement {
             {
                 new OpenApiSecurityScheme {
                     Reference = new OpenApiReference {
                         Type = ReferenceType.SecurityScheme,
                             Id = "Bearer"
                     }
                 },
                 new string[] {}
             }

          });
         builder.Services.AddHttpContextAccessor();
     });
 
 builder.Services.AddCustomConfiguration(configuration);
         if (ApplicationSettings.AppInsightConfig is null)
         {
             ApplicationSettings.AppInsightConfig = new();
             ApplicationSettings.AppInsightConfig.InstrumentationKey =
                 
configuration.GetSection("ApplicationInsights").GetSection("InstrumentationKey").Value;
             ApplicationSettings.AppInsightConfig.ConnectionString =
                    
configuration.GetSection("ApplicationInsights").GetSection("ConnectionString").Value;
         }
         builder.Services.AddServiceDependencies(ApplicationSettings);

         //builder.WebHost.ConfigureKestrel((context, serverOptions) =>
         //{
         //    serverOptions.Listen(IPAddress.Any, 5000);
         //});


         builder.Services.AddLogging(builder =>
         {
             // Only Application Insights is registered as a logger provider
             builder.AddApplicationInsights(
                 configureTelemetryConfiguration:
                 (config) => config.ConnectionString = 
            configuration["ApplicationInsights:ConnectionString"],
                 configureApplicationInsightsLoggerOptions: (options) => { }
             );
         });

         var app = builder.Build();

         GrpcAdapterExtention.AddServiceConfigurations(app);
     //app.Use(async (context, next) =>
     //{
     //    if (context.Request.Path.StartsWithSegments("/swagger")
     //        && !context.User.Identity.IsAuthenticated)
     //    {
     //        context.Response.Redirect("/Identity/Account/Login");
     //        return;
     //    }
     //    await next();
     //});
     app.UseAuthentication();
     app.UseAuthorization();
     app.MapRazorPages();
     app.UseStaticFiles();
     app.UseSwagger();
         app.UseSwaggerUI();
         app.UseSwagger(c =>
         {
             c.RouteTemplate = "cabinetGatewaySvc/swagger/{documentname}/swagger.json";
         });


         app.UseSwaggerUI(c =>
         {
             c.SwaggerEndpoint("/cabinetGatewaySvc/swagger/v1/swagger.json", "Cabinet 
         Gateway Microservice");
             c.RoutePrefix = "cabinetGatewaySvc/swagger";
         });

         app.UseRouting();


         app.UseEndpoints(endpoints =>
         {
             _ = endpoints.MapControllers();
         });
         app.Run();

     
  }
  }

5

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật