Example #1
0
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (context.GetControllerAndActionAttributes <AllowAnonymousAttribute>().Any())
            {
                return;
            }

            var actionAttributes = context.GetControllerAndActionAttributes <T>();

            if (!actionAttributes.Any())
            {
                return;
            }

            if (includeUnauthorizedAndForbiddenResponses)
            {
                operation.Responses.Add("401", new Response {
                    Description = "Unauthorized"
                });
                operation.Responses.Add("403", new Response {
                    Description = "Forbidden"
                });
            }

            var policies = policySelector(actionAttributes) ?? Enumerable.Empty <string>();

            operation.Security = new List <IDictionary <string, IEnumerable <string> > >
            {
                new Dictionary <string, IEnumerable <string> >
                {
                    { "oauth2", policies }
                }
            };
        }
Example #2
0
        /// <summary>
        /// 重写操作处理
        /// </summary>
        /// <param name="operation">当前操作</param>
        /// <param name="context">操作过滤器器上下文</param>
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var swaggerRequestHeaders = context.GetControllerAndActionAttributes <SwaggerRequestHeaderAttribute>().ToList();

            if (!swaggerRequestHeaders.Any())
            {
                return;
            }
            foreach (var requestHeader in swaggerRequestHeaders)
            {
                if (operation.Parameters == null)
                {
                    operation.Parameters = new List <IParameter>();
                }
                var request =
                    operation.Parameters.FirstOrDefault(x => x.In == "header" && x.Name == requestHeader.Name);
                if (request != null)
                {
                    operation.Parameters.Remove(request);
                }
                operation.Parameters.Add(new NonBodyParameter()
                {
                    Name        = requestHeader.Name,
                    In          = "header",
                    Description = requestHeader.Description,
                    Required    = requestHeader.Required,
                    Type        = "string",
                    Default     = requestHeader.Default
                });
            }
        }
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var actionAttributes = context.GetControllerAndActionAttributes <SwaggerResponseHeaderAttribute>();

            foreach (var attr in actionAttributes)
            {
                foreach (var statusCode in attr.StatusCodes)
                {
                    var response = operation.Responses.FirstOrDefault(x => x.Key == (statusCode).ToString(CultureInfo.InvariantCulture)).Value;

                    if (response != null)
                    {
                        if (response.Headers == null)
                        {
                            response.Headers = new Dictionary <string, OpenApiHeader>();
                        }

                        response.Headers.Add(attr.Name, new OpenApiHeader {
                            Description = attr.Description, Schema = new OpenApiSchema {
                                Description = attr.Description, Type = attr.Type, Format = attr.Format
                            }
                        });
                    }
                }
            }
        }
        /// <summary>
        /// 重写操作处理
        /// </summary>
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var swaggerRequestHeaders = context.GetControllerAndActionAttributes <SwaggerRequestHeaderAttribute>().ToList();

            if (!swaggerRequestHeaders.Any())
            {
                return;
            }
            foreach (var requestHeader in swaggerRequestHeaders)
            {
                if (operation.Parameters == null)
                {
                    operation.Parameters = new List <OpenApiParameter>();
                }
                var request = operation.Parameters.FirstOrDefault(x =>
                                                                  x.In == ParameterLocation.Header && x.Name == requestHeader.Name);
                if (request != null)
                {
                    operation.Parameters.Remove(request);
                }
                operation.Parameters.Add(new OpenApiParameter()
                {
                    Name        = requestHeader.Name,
                    In          = ParameterLocation.Header,
                    Required    = requestHeader.Required,
                    Description = requestHeader.Description,
                    Schema      = new OpenApiSchema()
                    {
                        Type    = "string",
                        Default = new OpenApiString(requestHeader.Default?.ToString())
                    }
                });
            }
        }
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            if (context.GetControllerAndActionAttributes <AllowAnonymousAttribute>().Any())
            {
                return;
            }

            var actionAttributes = context.GetControllerAndActionAttributes <T>();

            if (!actionAttributes.Any())
            {
                return;
            }

            if (includeUnauthorizedAndForbiddenResponses)
            {
                if (!operation.Responses.ContainsKey("401"))
                {
                    operation.Responses.Add("401", new OpenApiResponse {
                        Description = "Unauthorized"
                    });
                }

                if (!operation.Responses.ContainsKey("403"))
                {
                    operation.Responses.Add("403", new OpenApiResponse {
                        Description = "Forbidden"
                    });
                }
            }

            var policies = policySelector(actionAttributes) ?? Enumerable.Empty <string>();

            operation.Security = new List <OpenApiSecurityRequirement>
            {
                new OpenApiSecurityRequirement
                {
                    { new OpenApiSecurityScheme {
                          Reference = new OpenApiReference {
                              Type = ReferenceType.SecurityScheme, Id = securitySchemaName
                          }
                      }, policies.ToList() }
                }
            };
        }
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (context.GetControllerAndActionAttributes <AllowAnonymousAttribute>().Any())
            {
                return;
            }

            var authorizeAttributes = context.GetControllerAndActionAttributes <AuthorizeAttribute>();

            if (authorizeAttributes.Any())
            {
                var authorizationDescription = new StringBuilder(" (Auth");

                AppendPolicies(authorizeAttributes, authorizationDescription);
                AppendRoles(authorizeAttributes, authorizationDescription);

                operation.Summary += authorizationDescription.ToString().TrimEnd(';') + ")";
            }
        }
Example #7
0
        /// <inheritdoc />
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var lastControllerVersion = context.GetControllerAndActionAttributes <ApiVersionAttribute>().Where(apiVer => apiVer.Deprecated);

            if (!lastControllerVersion.Any())
            {
                return;
            }

            operation.Deprecated = true;
        }
        private void SetResponseExamples(OpenApiOperation operation, OperationFilterContext context)
        {
            var actionAttributes      = context.GetControllerAndActionAttributes <SwaggerResponseExampleAttribute>().Select(a => new StatusCodeWithType(a.StatusCode, a.ExamplesProviderType));
            var responseAttributes    = context.GetControllerAndActionAttributes <ProducesResponseTypeAttribute>().Select(a => new StatusCodeWithType(a.StatusCode, a.Type));
            var autodetectedResponses = context.ApiDescription.SupportedResponseTypes.Select(r => new StatusCodeWithType(r.StatusCode, r.Type));

            var responses = responseAttributes.Concat(autodetectedResponses);

            foreach (var response in responses)
            {
                if (actionAttributes.Any(a => a.StatusCode == response.StatusCode))
                {
                    continue; // if [SwaggerResponseExample] is defined, then let ExamplesOperationFilter define the example
                }

                var example = serviceProvider.GetExampleForType(response.Type);

                responseExample.SetResponseExampleForStatusCode(operation, response.StatusCode, example);
            }
        }
Example #9
0
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (context.GetControllerAndActionAttributes <AllowAnonymousAttribute>().Any())
        {
            return;
        }

        IEnumerable <T> actionAttributes = context.GetControllerAndActionAttributes <T>();

        if (!actionAttributes.Any())
        {
            return;
        }

        if (_includeUnauthorizedAndForbiddenResponses)
        {
            if (!operation.Responses.ContainsKey(UnauthorizedStatusCode))
            {
                operation.Responses.Add(UnauthorizedStatusCode, _unauthorizedResponse);
            }

            if (!operation.Responses.ContainsKey(ForbiddenStatusCode))
            {
                operation.Responses.Add(ForbiddenStatusCode, _forbiddenResponse);
            }
        }

        IEnumerable <string> policies = _policySelector(actionAttributes) ?? Enumerable.Empty <string>();

        operation.Security.Add(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme {
                    Reference = new OpenApiReference {
                        Type = ReferenceType.SecurityScheme, Id = _securitySchemaName
                    }
                },
                policies.ToList()
            }
        });
    }
Example #10
0
        private void SetResponseModelExamples(Operation operation, OperationFilterContext context)
        {
            var responseAttributes = context.GetControllerAndActionAttributes <SwaggerResponseExampleAttribute>();

            foreach (var attr in responseAttributes)
            {
                var examplesProvider = (IExamplesProvider)(serviceProvider.GetService(attr.ExamplesProviderType)
                                                           ?? Activator.CreateInstance(attr.ExamplesProviderType));

                object example = examplesProvider?.GetExamples();

                responseExample.SetResponseExampleForStatusCode(operation, attr.StatusCode, example, attr.ContractResolver, attr.JsonConverter);
            }
        }
        private void SetResponseExamples(OpenApiOperation operation, OperationFilterContext context)
        {
            var responseAttributes = context.GetControllerAndActionAttributes <SwaggerResponseExampleAttribute>();

            foreach (var attr in responseAttributes)
            {
                var example = serviceProvider.GetExampleWithExamplesProviderType(attr.ExamplesProviderType);

                responseExample.SetResponseExampleForStatusCode(
                    operation,
                    attr.StatusCode,
                    example);
            }
        }
Example #12
0
        /// <inheritdoc />
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var controllerScopes = context.GetControllerAndActionAttributes <AuthorizeAttribute>().Select(attr => attr.Policy);
            var requiredPolicies = controllerScopes.Distinct().ToList();

            if (!requiredPolicies.Any())
            {
                return;
            }

            operation.Responses.Add("401", new OpenApiResponse {
                Description = "Unauthorized"
            });
            operation.Responses.Add("403", new OpenApiResponse {
                Description = "Forbidden"
            });

            var requiredScopes = new List <string>();

            foreach (var policy in requiredPolicies)
            {
                requiredScopes.AddRange(GetPolicyScopes(policy));
            }

            operation.Description += $"\n\r<b>Required OAuth2 Scopes:</b> <i>{string.Join(", ", requiredScopes)}</i>";

            // Only setting this to get the padlock display
            operation.Security.Add(new OpenApiSecurityRequirement
            {
                { new OpenApiSecurityScheme {
                      Reference = new OpenApiReference {
                          Type = ReferenceType.SecurityScheme, Id = "oauth2"
                      }
                  }, requiredPolicies.ToList() }
            });

            operation.Parameters.Add(
                new OpenApiParameter
            {
                Name        = "Authorization",
                In          = ParameterLocation.Header,
                Description = "Bearer {access token}",
                Required    = true,
                Schema      = new OpenApiSchema
                {
                    Type = "string"
                }
            });
        }
        private void SetRequestExamples(OpenApiOperation operation, OperationFilterContext context)
        {
            var actionAttributes = context.GetControllerAndActionAttributes <SwaggerRequestExampleAttribute>();

            foreach (var attr in actionAttributes)
            {
                var example = serviceProvider.GetExampleWithExamplesProviderType(attr.ExamplesProviderType);

                requestExample.SetRequestExampleForOperation(
                    operation,
                    context.SchemaRepository,
                    attr.RequestType,
                    example);
            }
        }
        private void SetRequestExamples(OpenApiOperation operation, OperationFilterContext context)
        {
            var actionAttributes = context.GetControllerAndActionAttributes <SwaggerRequestExampleAttribute>();

            foreach (var parameterDescription in context.ApiDescription.ParameterDescriptions)
            {
                if (actionAttributes.Any(a => a.RequestType == parameterDescription.Type))
                {
                    continue; // if [SwaggerRequestExample] is defined, then let ExamplesOperationFilter define the example
                }

                var example = serviceProvider.GetExampleForType(parameterDescription.Type);

                requestExample.SetRequestExampleForOperation(operation, context.SchemaRepository, parameterDescription.Type, example);
            }
        }
        private void SetResponseExamples(Operation operation, OperationFilterContext context)
        {
            var actionAttributes   = context.MethodInfo.GetCustomAttributes <SwaggerResponseExampleAttribute>();
            var responseAttributes = context.GetControllerAndActionAttributes <ProducesResponseTypeAttribute>();

            foreach (var response in responseAttributes)
            {
                if (actionAttributes.Any(a => a.StatusCode == response.StatusCode))
                {
                    continue; // if [SwaggerResponseExample] is defined, then let ExamplesOperationFilter define the example
                }

                var example = GetExampleForTypeFromServiceProvider(response.Type);

                responseExample.SetResponseExampleForStatusCode(operation, response.StatusCode, example);
            }
        }
Example #16
0
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                operation.Parameters = new List <IParameter>();
            }

            if (context.GetControllerAndActionAttributes <RequireCallbackUrlFilter>().Any())
            {
                operation.Parameters.Add(new NonBodyParameter
                {
                    Name        = HttpRequestHeaders.RequestUrl,
                    In          = "header",
                    Type        = "string",
                    Required    = true, // set to false if this is optional,
                    Description = "Request Callback Url value (Use for email links etc.)"
                });
            }
        }
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                operation.Parameters = new List <OpenApiParameter>();
            }

            var parameterAttributes = context
                                      .GetControllerAndActionAttributes <HeaderParameterAttribute>()
                                      .ToList();

            var aggregatedHeaders = new List <IHeaderParameter>(_apiConfig.HeaderParameters);

            aggregatedHeaders.AddRange(parameterAttributes);

            foreach (var attr in aggregatedHeaders.Merge(x => x.Name))
            {
                operation
                .Parameters
                .Add
                (
                    new OpenApiParameter
                {
                    AllowEmptyValue = attr.AllowEmptyValue,
                    Deprecated      = attr.Deprecated,
                    Description     = attr.Description,
                    In            = ParameterLocation.Header,
                    Name          = attr.Name,
                    Required      = attr.Required,
                    Example       = new OpenApiString(attr.Example ?? string.Empty),
                    AllowReserved = attr.AllowReserved,
                    Explode       = attr.Explode,
                    Schema        = string.IsNullOrWhiteSpace(attr.Type)
                                        ? null
                                        : new OpenApiSchema {
                        Type = attr.Type, Format = attr.Format
                    }
                }
                );
            }
        }
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            void Apply <TAttribute, TOptions, TIOptions>(TOptions optionsClone, TOptions source)
                where TAttribute : AbstractTrackingAttribute, TIOptions
                where TOptions : AbstractOptions, TIOptions

            {
                var attributes = context
                                 .GetControllerAndActionAttributes <TAttribute>()
                                 ?.ToList();

                optionsClone.Merge(source);

                if (attributes != null && attributes.Any())
                {
                    foreach (var attribute in attributes)
                    {
                        optionsClone.Merge <TOptions, TIOptions, TAttribute>(attribute);
                    }
                }

                foreach (var item in optionsClone.ToDictionary())
                {
                    operation.Extensions[item.Key] = item.Value;
                }
            }

            XAmazonApiGatewayIntegrationOptions CreateDefaultIntegrationOptions(OperationFilterContext ctx, string baseUri)
            {
                var requestParameters =
                    ctx
                    .ApiDescription
                    .ParameterDescriptions
                    .Where(x => x.Source == BindingSource.Path)
                    .ToDictionary
                    (
                        key => $"integration.request.path.{key.Name}",
                        value => $"method.request.path.{value.Name}"
                    )
                    .Union
                    (
                        context
                        .GetControllerAndActionAttributes <XAmazonApiGatewayIntegrationRequestParameterAttribute>()
                        .ToDictionary(key => key.IntegrationRequestParameter, value => value.MethodRequestParameter)
                    );

                return(new XAmazonApiGatewayIntegrationOptions
                {
                    HttpMethod = ctx.ApiDescription.HttpMethod,
                    Uri = Uri.IsWellFormedUriString(baseUri, UriKind.RelativeOrAbsolute)
                            ? new Uri(new Uri(baseUri), ctx.ApiDescription.RelativePath).ToString()
                            : $@"{baseUri}{(baseUri.EndsWith("/") ? string.Empty : "/")}{ctx.ApiDescription.RelativePath}",
                    RequestParameters = _options.IntegrationOptions.RequestParameters.Union(requestParameters)
                });
            }

            Apply <XAmazonApiGatewayIntegrationAttribute, XAmazonApiGatewayIntegrationOptions, IXAmazonApiGatewayIntegrationOptions>
            (
                CreateDefaultIntegrationOptions(context, _options.IntegrationOptions.BaseUri),
                _options.IntegrationOptions
            );

            Apply <XAmazonApiGatewayAuthAttribute, XAmazonApiGatewayAuthOptions, IXAmazonApiGatewayAuthOptions>
            (
                new XAmazonApiGatewayAuthOptions(),
                _options.AuthOptions
            );

            Apply <XAmazonApiGatewayRequestValidatorAttribute, XAmazonApiGatewayRequestValidatorOptions, IXAmazonApiGatewayRequestValidatorOptions>
            (
                new XAmazonApiGatewayRequestValidatorOptions(),
                null
            );
        }
Example #19
0
        /// <inheritdoc />
        public void Apply(Operation operation, OperationFilterContext context)
        {
            Dictionary <string, IEnumerable <string> > policy = new Dictionary <string, IEnumerable <string> >();

            if (!context.GetControllerAndActionAttributes <AllowNoAccessToken>().Any())
            {
                var allAccessTokenActions = context.GetControllerAndActionAttributes <TAccessToken>();
                var atAttributes          = allAccessTokenActions as TAccessToken[] ?? allAccessTokenActions.ToArray();
                if (!atAttributes.Any())
                {
                    return;
                }

                var accessTokenPolicies = _accessTokenPolicySelector(atAttributes) ?? System.Linq.Enumerable.Empty <string>();
                var tokenPolicies       = accessTokenPolicies as string[] ?? accessTokenPolicies.ToArray();
                if (tokenPolicies.Any())
                {
                    if (_includeForbiddenResponses && !operation.Responses.ContainsKey("412"))
                    {
                        operation.Responses.Add("412",
                                                new Response
                        {
                            Description = "Precondition Failed",
                            //Examples = new ApiResponse(false, ErrorMessages.InvalidApiKey, null)
                        });
                    }
                    //operation.Responses.Add("403",
                    //    new Response
                    //    {
                    //        Description =
                    //            JsonConvert.SerializeObject(new ApiResponse(false, ErrorMessages.InvalidApiKey,
                    //                null))
                    //    });

                    policy.Add($"{HttpRequestHeaders.ApiKey}_{_groupName}", tokenPolicies);
                }
            }


            if (!context.GetControllerAndActionAttributes <AllowAnonymousAttribute>().Any())
            {
                var actionAttributes = context.GetControllerAndActionAttributes <TAuthorize>();
                var attributes       = actionAttributes as TAuthorize[] ?? actionAttributes.ToArray();
                if (!attributes.Any())
                {
                    return;
                }

                if (_includeUnauthorizedResponses && !operation.Responses.ContainsKey("401"))
                {
                    operation.Responses.Add("401",
                                            new Response
                    {
                        Description = "Unauthorized",
                        //Examples = new ApiResponse401Example()
                    });
                }
                //operation.Responses.Add("401", new Response { Description = JsonConvert.SerializeObject(new ApiResponse(false, ErrorMessages.UnAuthorized, null)) });

                var authorizePolicies = _authorizePolicySelector(attributes) ?? System.Linq.Enumerable.Empty <string>();

                policy.Add($"oauth2_{_groupName}", authorizePolicies);
            }

            if (policy.Any())
            {
                operation.Security = new List <IDictionary <string, IEnumerable <string> > >
                {
                    policy
                };
            }
        }