Skip to content

Commit 0341b81

Browse files
authored
Merge pull request #5 from Svetloslav15/snovoselski/remove-lock-icon-for-anonymous-endpoints
fix(swagger): remove lock icon for anonymous users
2 parents 91f8170 + bc91043 commit 0341b81

File tree

2 files changed

+39
-14
lines changed

2 files changed

+39
-14
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
namespace NorthwindCRUD.Filters
2+
{
3+
using Microsoft.AspNetCore.Authorization;
4+
using Microsoft.OpenApi.Models;
5+
using Swashbuckle.AspNetCore.SwaggerGen;
6+
7+
public class AuthResponsesOperationFilter : IOperationFilter
8+
{
9+
public void Apply(OpenApiOperation operation, OperationFilterContext context)
10+
{
11+
var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
12+
.Union(context.MethodInfo.GetCustomAttributes(true))
13+
.OfType<AuthorizeAttribute>();
14+
15+
if (authAttributes.Any())
16+
{
17+
var securityRequirement = new OpenApiSecurityRequirement()
18+
{
19+
{
20+
new OpenApiSecurityScheme
21+
{
22+
Reference = new OpenApiReference
23+
{
24+
Type = ReferenceType.SecurityScheme,
25+
Id = "Bearer"
26+
}
27+
},
28+
new List<string>()
29+
}
30+
};
31+
operation.Security = new List<OpenApiSecurityRequirement> { securityRequirement };
32+
operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
33+
}
34+
}
35+
}
36+
}

NorthwindCRUD/Program.cs

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
using NorthwindCRUD.Helpers;
1111
using NorthwindCRUD.Services;
1212
using System.Text;
13+
using NorthwindCRUD.Filters;
1314

1415
var builder = WebApplication.CreateBuilder(args);
1516
var AllowAnyOriginPolicy = "_allowAnyOrigin";
@@ -36,20 +37,8 @@
3637
BearerFormat = "JWT",
3738
Scheme = "bearer"
3839
});
39-
option.AddSecurityRequirement(new OpenApiSecurityRequirement
40-
{
41-
{
42-
new OpenApiSecurityScheme
43-
{
44-
Reference = new OpenApiReference
45-
{
46-
Type=ReferenceType.SecurityScheme,
47-
Id="Bearer"
48-
}
49-
},
50-
new string[]{}
51-
}
52-
});
40+
41+
option.OperationFilter<AuthResponsesOperationFilter>();
5342
});
5443

5544
builder.Services.AddCors(options =>

0 commit comments

Comments
 (0)