File tree Expand file tree Collapse file tree 2 files changed +39
-14
lines changed
Expand file tree Collapse file tree 2 files changed +39
-14
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 1010using NorthwindCRUD . Helpers ;
1111using NorthwindCRUD . Services ;
1212using System . Text ;
13+ using NorthwindCRUD . Filters ;
1314
1415var builder = WebApplication . CreateBuilder ( args ) ;
1516var AllowAnyOriginPolicy = "_allowAnyOrigin" ;
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
5544builder . Services . AddCors ( options =>
You can’t perform that action at this time.
0 commit comments