public void Apply(Operation operation, OperationFilterContext context) { // Check for authorize attribute context.ApiDescription.TryGetMethodInfo(out var methodInfo); if (methodInfo == null) { return; } PtmsAuthorize ptmsAttribute = null; if (methodInfo.MemberType == MemberTypes.Method) { ptmsAttribute = methodInfo.GetCustomAttributes(true).OfType <PtmsAuthorize>().LastOrDefault() ?? methodInfo.DeclaringType.GetCustomAttributes(true).OfType <PtmsAuthorize>().LastOrDefault(); if (ptmsAttribute != null) { var allowAnonymous = methodInfo.GetCustomAttributes(true).OfType <AllowAnonymousAttribute>().Any(); if (allowAnonymous) { ptmsAttribute = null; } } } 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 += " Доступно анонимно"; } }
internal static PtmsAuthorize GetAuthorizeAttribute(MethodInfo methodInfo) { PtmsAuthorize ptmsAttribute = null; if (methodInfo.MemberType == MemberTypes.Method) { ptmsAttribute = methodInfo.GetCustomAttributes(true).OfType <PtmsAuthorize>().LastOrDefault() ?? methodInfo.DeclaringType.GetCustomAttributes(true).OfType <PtmsAuthorize>().LastOrDefault(); if (ptmsAttribute != null) { var allowAnonymous = methodInfo.GetCustomAttributes(true).OfType <AllowAnonymousAttribute>().Any(); if (allowAnonymous) { ptmsAttribute = null; } } } return(ptmsAttribute); }