public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation.parameters == null) return;

            HandleFromUriArrayParams(operation);
            HandleFromUriObjectParams(operation, schemaRegistry, apiDescription);
        }
 public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
 {
     if (operation.operationId == "FileDownload_GetFile")
     {
         operation.produces = new[] { "application/octet-stream" };
     }
 }
        public void HeaderFilter_AddsHeaderRequirement(Collection<IFilter> filters)
        {
            // Arrange
            var swashbuckleFilter = new MobileAppHeaderFilter();
            var operation = new Operation();

            var controllerDescMock = new Mock<HttpControllerDescriptor>();
            controllerDescMock.Setup(c => c.GetFilters()).Returns(filters);

            var description = new ApiDescription();
            description.ActionDescriptor = new ReflectedHttpActionDescriptor();
            description.ActionDescriptor.ControllerDescriptor = controllerDescMock.Object;

            // Act
            swashbuckleFilter.Apply(operation, null, description);

            // Assert
            Assert.NotNull(operation.parameters);
            Assert.Equal(1, operation.parameters.Count);
            Parameter parameter = operation.parameters[0];
            Assert.Equal("ZUMO-API-VERSION", parameter.name);
            Assert.Equal("header", parameter.@in);
            Assert.Equal("string", parameter.type);
            Assert.Equal("2.0.0", parameter.@default);
            Assert.True(parameter.required);
        }
 /// <summary>
 ///  Implement the interace of operation filter
 /// </summary>
 /// <param name="operation"></param>
 /// <param name="schemaRegistry"></param>
 /// <param name="apiDescription"></param>
 public void Apply(Operation operation, SchemaRegistry schemaRegistry, System.Web.Http.Description.ApiDescription apiDescription)
 {
     if (operation != null && operation.responses != null && operation.responses.ContainsKey("202"))
     {
         operation.responses["202"].schema = null;
     }
 }
        public void Apply(Operation operation, OperationFilterContext context)
        {
            // Correspond each "Authorize" role to an oauth2 scope
            var controllerScopes = context.ApiDescription.GetControllerAttributes()
                .OfType<AuthorizeAttribute>()
                .SelectMany(attr => attr.Roles.Split(','));

            var actionScopes = context.ApiDescription.GetActionAttributes()
                .OfType<AuthorizeAttribute>()
                .SelectMany(attr => attr.Roles.Split(','));

            var scopes = controllerScopes.Union(actionScopes).Distinct();

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

                var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
                {
                    { "oauth2", scopes }
                };

                operation.Security.Add(oAuthRequirements);
            }
        }
Exemple #6
0
 public void Apply(Swashbuckle.Swagger.Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
 {
     if (operation.parameters != null)
     {
         operation.parameters.Add(new Parameter
         {
             name        = "Authorization",
             @in         = "header",
             description = "access token",
             required    = false,
             type        = "string"
         });
     }
     else
     {
         operation.parameters = new List <Swashbuckle.Swagger.Parameter>()
         {
             new Parameter {
                 name        = "Authorization",
                 @in         = "header",
                 description = "access token",
                 required    = false,
                 type        = "string"
             }
         };
     }
 }
Exemple #7
0
        public void Apply(Swashbuckle.Swagger.Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation == null)
            {
                return;
            }

            if (operation.parameters == null)
            {
                operation.parameters = new List <Parameter>();
            }

            var parameter = new Parameter
            {
                description = "The authorization token",
                @in         = "header",
                name        = "Authorization",
                required    = true,
                type        = "string"
            };

            if (apiDescription.GetControllerAndActionAttributes <AuthAttribute>().Any())
            {
                operation.parameters.Add(parameter);
            }
        }
        private void RemoveVersionParamFrom(Operation operation)
        {
            if (operation == null) return;

            var versionParam = operation.parameters.SingleOrDefault(param => param.name == "apiVersion");
            if (versionParam != null) operation.parameters.Remove(versionParam);
        }
        public void MobileAppAuthFilter_AddsSecurity_WhenAuthorizeSpecified()
        {
            // Arrange
            var filter = new MobileAppAuthenticationFilter("facebook");

            var operation = new Operation();
            var apiDescription = new ApiDescription();
            var actionDescMock = new Mock<HttpActionDescriptor>();
            Collection<FilterInfo> pipeline = new Collection<FilterInfo>()
            {
                new FilterInfo(new AuthorizeAttribute(), FilterScope.Action)
            };
            actionDescMock.Setup(a => a.GetFilterPipeline()).Returns(pipeline);
            apiDescription.ActionDescriptor = actionDescMock.Object;

            // Act
            filter.Apply(operation, null, apiDescription);

            // Assert
            Assert.NotNull(operation.security);
            Assert.Equal(1, operation.security.Count);
            Assert.Equal(1, operation.security[0].Keys.Count);
            Assert.Equal("facebook", operation.security[0].Keys.First());
            Assert.Equal(0, operation.security[0]["facebook"].Count());
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            // Determine if the operation has the Authorize attribute
            var authorizeAttributes = apiDescription
                .ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>();

            if (!authorizeAttributes.Any())
                return;

            // Correspond each "Authorize" role to an oauth2 scope
            var scopes =
                authorizeAttributes
                .SelectMany(attr => attr.Roles.Split(','))
                .Distinct()
                .ToList();

            // Initialize the operation.security property if it hasn't already been
            if (operation.security == null)
                operation.security = new List<IDictionary<string, IEnumerable<string>>>();

            var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
                {
                    { "oauth2", scopes }
                };

            operation.security.Add(oAuthRequirements);
        }
 public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
 {
     var successResponse = operation.responses["200"];
     successResponse.examples = new Dictionary<string, object>
     {
         {"application/json", new {title = "A message", content = "Some content"}}
     };
 }
            public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
            {
                var descriptor = apiDescription.ActionDescriptor as ControllerlessActionDescriptor;

                operation.summary = descriptor != null
                    ? this.provider.GetDescription(descriptor.MessageType)
                    : operation.summary;
            }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation.operationId != "Products_GetAllByType") return;

            var response = operation.responses["200"];
            response.vendorExtensions = new Dictionary<string, object>();
            response.vendorExtensions.Add("x-foo", "bar");
        }
Exemple #14
0
        private void RemoveVersionParamFrom(Operation operation)
        {
            if (operation == null || operation.Parameters == null) return;

            var versionParam = operation.Parameters.FirstOrDefault(param => param.Name == "version");
            if (versionParam == null) return;

            operation.Parameters.Remove(versionParam) ;
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var errorSchema = schemaRegistry.GetOrRegister(typeof(HttpError));

            operation.responses.Add("200", new Response
            {
                description = "Ok",
                schema = errorSchema
            });
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            Contract.Assume(operation != null);
            Contract.Assume(schemaRegistry != null);
            Contract.Assume(apiDescription != null);

            if (HasEnableQueryAttribute(apiDescription) && !HasAnyQueryOptionParameters(operation))
            {
                operation.parameters = ODataSwaggerUtilities.AddQueryOptionParameters(operation.parameters ?? new List<Parameter>());
            }
        }
 public void Apply(Operation operation, DataTypeRegistry dataTypeRegistry, ApiDescription apiDescription)
 {
     if (apiDescription.ActionDescriptor.GetFilters().OfType<AuthorizeAttribute>().Any())
     {
         operation.ResponseMessages.Add(new ResponseMessage
         {
             Code = (int)HttpStatusCode.Unauthorized,
             Message = "Authentication required"
         });
     }
 }
        private static void HandleFromUriArrayParams(Operation operation)
        {
            var fromUriArrayParams = operation.parameters
                .Where(param => param.@in == "query" && param.type == "array")
                .ToArray();

            foreach (var param in fromUriArrayParams)
            {
                param.collectionFormat = "multi";
            }
        }
		public void Apply(Operation operation, SchemaRegistry schemaRegistry, System.Web.Http.Description.ApiDescription apiDescription)
		{
			operation.parameters = operation.parameters ?? new List<Parameter>();
			operation.parameters.Add(new Parameter
			{
				name = Name,
				description = Description,
				@in = In,
				required = true,
				type = "string"
			});
		}
        private List<ApiParameterDescription> CreateParameterDescriptions(Operation operation, HttpActionDescriptor actionDescriptor)
        {
            Contract.Requires(operation != null);
            Contract.Requires(actionDescriptor != null);

            return operation.parameters?
                .Select((parameter, index) => GetParameterDescription(parameter, index, actionDescriptor))
                // Concat reflected parameter descriptors to ensure that parameters are not missed
                // e.g., parameters not described by or derived from the EDM model.
                .Concat(CreateParameterDescriptions(actionDescriptor))
                .Distinct(new ApiParameterDescriptionEqualityComparer())
                .ToList();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ODataActionDescriptor" /> class.
        /// </summary>
        /// <param name="actionDescriptor">The HTTP action descriptor.</param>
        /// <param name="route">The OData route.</param>
        /// <param name="relativePathTemplate">The relative path template.</param>
        /// <param name="request">The request.</param>
        /// <param name="operation">Additional metadata based about the action.</param>
        public ODataActionDescriptor(HttpActionDescriptor actionDescriptor, ODataRoute route, string relativePathTemplate, HttpRequestMessage request, Operation operation = null)
        {
            Contract.Requires(actionDescriptor != null);
            Contract.Requires(route != null);
            Contract.Requires(relativePathTemplate != null);
            Contract.Requires(request != null);

            ActionDescriptor = actionDescriptor;
            Route = route;
            RelativePathTemplate = relativePathTemplate;
            Request = request;
            Operation = operation;
        }
        /// <summary>
        /// Implement the Apply method in IOperationFilter to define response codes specific to the API
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="dataTypeRegistry"></param>
        /// <param name="apiDescription"></param>
        public void Apply(Operation operation, DataTypeRegistry dataTypeRegistry, ApiDescription apiDescription)
        {
            operation.ResponseMessages.Add(new ResponseMessage
            {
                Code = (int)HttpStatusCode.OK,
                Message = "It's all good!"
            });

            operation.ResponseMessages.Add(new ResponseMessage
            {
                Code = (int)HttpStatusCode.InternalServerError,
                Message = "Somethings up!"
            });
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {

            //Find current Route name
            string routeTemplate = apiDescription.Route.RouteTemplate;
            string BaseRouteName = routeTemplate.Substring(0, routeTemplate.IndexOf('/'));
            string postfix = "_" + BaseRouteName + "_Route";

            // Set the operation id to match the format "OperationThroughRouteName"
            operation.operationId = string.Format(
                "{0}_Through{1}",
                operation.operationId,
                postfix);

        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation.parameters == null) return;

            var queryEnumParams = operation.parameters
                .Where(param => param.@in == "query" && param.@enum != null)
                .ToArray();

            foreach (var param in queryEnumParams)
            {
                param.items = new PartialSchema { type = param.type, @enum = param.@enum };
                param.type = "array";
                param.collectionFormat = "csv";
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="schemaRegistry"></param>
        /// <param name="apiDescription"></param>
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation.parameters != null)
            {
                // Select the capitalized parameter names
                var parameters = operation.parameters.Select(
                    p => CultureInfo.InvariantCulture.TextInfo.ToTitleCase(p.name));

                // Set the operation id to match the format "OperationByParam1AndParam2"
                operation.operationId = string.Format(
                    "{0}By{1}",
                    operation.operationId,
                    string.Join("And", parameters));
            }
        }
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation.parameters != null)
            {
                // Select the capitalized parameter names
                var parameters = operation.parameters.Select(
                    p => CultureInfo.InvariantCulture.TextInfo.ToTitleCase(p.name));

                // Set the operation id to match the format "OperationByParam1AndParam2"
                operation.operationId = string.Format(
                    "{0}By{1}",
                    operation.operationId,
                    string.Join("And", parameters));
            }
        }
Exemple #27
0
 public void Apply(Swashbuckle.Swagger.Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
 {
     if (operation.operationId == "Poi_PostFile") // controller and action name
     {
         operation.consumes.Add("multipart/form-data");
         operation.parameters = new List <Parameter>();
         operation.parameters.Add(new Parameter
         {
             name     = "file",
             @in      = "formData",
             required = true,
             type     = "file"
         }
                                  );
     }
 }
        public void MobileAppAuthFilter_DoesNotAddSecurity_WithoutAuthorizeSpecified()
        {
            // Arrange
            var filter = new MobileAppAuthenticationFilter("facebook");
            var operation = new Operation();
            var apiDescription = new ApiDescription();
            var actionDescMock = new Mock<HttpActionDescriptor>();
            actionDescMock.Setup(a => a.GetFilterPipeline()).Returns(new Collection<FilterInfo>());
            apiDescription.ActionDescriptor = actionDescMock.Object;

            // Act
            filter.Apply(operation, null, apiDescription);

            // Assert
            Assert.Null(operation.security);
        }
        public void Apply(Operation operation, DataTypeRegistry dataTypeRegistry, ApiDescription apiDescription)
        {
            var scopeIds = apiDescription.ActionDescriptor.GetFilterPipeline()
                .Select(filterInfo => filterInfo.Instance)
                .OfType<ScopeAuthorizeAttribute>()
                .SelectMany(attr => attr.Scopes)
                .Distinct();

            if (scopeIds.Any())
            {
                operation.Authorizations = new Dictionary<string, IList<Scope>>();
                operation.Authorizations["oauth2"] = scopeIds
                    .Select(id => new Scope { ScopeId = id })
                    .ToList();
            }
        }
 public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
 {
     if (operation.operationId == "FileUpload_PostFormData")
     {
         operation.consumes.Add("application/form-data");
         operation.parameters = new[]
         {
             new Parameter
             {
                 name = "file",
                 @in = "formData",
                 required = true,
                 type = "file"
             }
         };
     }
 }
 public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
 {
     if (operation.operationId == "BarCode_PostFormData")  // controller and action name
     {
         operation.consumes.Add("multipart/form-data");
         operation.parameters = new List<Parameter>
         {
             new Parameter
             {
                 name = "file",
                 required = true,
                 type = "file",
                 @in = "formData",
                 format = "image"
             }
         };
     }
 }
 public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
 {
     if (operation.operationId == "AssetUpload_PostFormData")  // controller and action name
     {
         operation.consumes.Add("multipart/form-data");
         operation.parameters = new List<Parameter>
         {
             new Parameter
             {
                 name = "file",
                 required = true,
                 type = "file",
                 @in = "formData",
                 vendorExtensions = new Dictionary<string, object> { {"x-ms-media-kind", "image" } }
             }
         };
     }
 }
        private void HandleFromUriObjectParams(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var fromUriObjectParams = operation.parameters
                .Where(param => param.@in == "query" && param.type == null)
                .ToArray();

            foreach (var objectParam in fromUriObjectParams)
            {
                var type = apiDescription.ParameterDescriptions
                    .Single(paramDesc => paramDesc.Name == objectParam.name)
                    .ParameterDescriptor.ParameterType;

                var refSchema = schemaRegistry.GetOrRegister(type);
                var schema = schemaRegistry.Definitions[[email protected]("#/definitions/", "")];

                ExtractAndAddQueryParams(schema, "", objectParam.required, schemaRegistry, operation.parameters);
                operation.parameters.Remove(objectParam);
            }
        }
Exemple #34
0
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            // Determine if the operation has the Authorize attribute
            var authorizeAttributes = apiDescription
                .ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>();

            if (!authorizeAttributes.Any())
                return;

            // Initialize the operation.security property
            if (operation.security == null)
                operation.security = new List<IDictionary<string, IEnumerable<string>>>();

            // Add the appropriate security definition to the operation
            var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
            {
                { "oauth2", Enumerable.Empty<string>() }
            };

            operation.security.Add(oAuthRequirements);
        }