public static void ConfigureSwagger(this IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc(DocAnonymousName, new Info { Version = "v1", Title = DocAnonymousName }); c.SwaggerDoc(DocAllName, new Info { Version = "v1", Title = DocAllName }); c.DocInclusionPredicate((docName, apiDesc) => { if (docName == DocAllName) { return(true); } if (docName == DocAnonymousName) { if (apiDesc.RelativePath.Contains("account/login") || apiDesc.RelativePath.Contains("account/register")) { return(false); } apiDesc.TryGetMethodInfo(out var methodInfo); if (methodInfo == null) { return(false); } var ptmsAttribute = SwaggerHelper.GetAuthorizeAttribute(methodInfo); return(ptmsAttribute == null); } return(false); }); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "Enter in the field below: \"Bearer {your-token}\". Get token from the /account/login", Name = "Authorization", In = "header", Type = "apiKey", }); c.OperationFilter <SwaggerAuthorizeCheckOperationFilter>(); }); }
public void Apply(Operation operation, OperationFilterContext context) { // Check for authorize attribute context.ApiDescription.TryGetMethodInfo(out var methodInfo); if (methodInfo == null) { return; } var ptmsAttribute = SwaggerHelper.GetAuthorizeAttribute(methodInfo); if (ptmsAttribute != null) { operation.Responses.Add(StatusCodes.Status401Unauthorized.ToString(), new Response { Description = "Unauthorized" }); operation.Responses.Add(StatusCodes.Status403Forbidden.ToString(), new Response { Description = "Forbidden" }); operation.Security = new List <IDictionary <string, IEnumerable <string> > > { new Dictionary <string, IEnumerable <string> > { { "Bearer", new string[] {} } } }; var rolesList = (ptmsAttribute.Roles != null && ptmsAttribute.Roles.Any()) ? string.Join(", ", ptmsAttribute.Roles) : "Любая"; operation.Summary += $" Роль: [{rolesList}]"; } else { operation.Summary += " Доступно анонимно"; } }