public void LoadSchemaReference()
        {
            // Arrange
            OpenApiDocument document;
            var             diagnostic = new OpenApiDiagnostic();

            using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "multipleReferences.v2.yaml")))
            {
                document = new OpenApiStreamReader().Read(stream, out diagnostic);
            }

            var reference = new OpenApiReference
            {
                Type = ReferenceType.Schema,
                Id   = "SampleObject"
            };

            // Act
            var referencedObject = document.ResolveReference(reference);

            // Assert
            referencedObject.Should().BeEquivalentTo(
                new OpenApiSchema
            {
                Required =
                {
                    "id",
                    "name"
                },
                Properties =
                {
                    ["id"] = new OpenApiSchema
                    {
                    Type   = "integer",
                    Format = "int64"
                    },
                    ["name"] = new OpenApiSchema
                    {
                    Type = "string"
                    },
                    ["tag"] = new OpenApiSchema
                    {
                    Type = "string"
                    }
                },
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.Schema,
                    Id   = "SampleObject"
                }
            }
                );
        }
Пример #2
0
        public void CanWriteReferenceObjectIntoJson()
        {
            // Arrange & Act
            string expect = @"
{
  ""$ref"": ""#/components/schemas/Pet""
}".Replace();

            OpenApiReference oar = new OpenApiReference("#/components/schemas/Pet");

            // Act & Assert
            Assert.Equal(expect, oar.WriteToJson());
        }
        private static OpenApiSecurityRequirement GetSecurityRequirement()
        {
            var reference = new OpenApiReference {
                Id = "Bearer", Type = ReferenceType.SecurityScheme
            };
            var securityScheme = new OpenApiSecurityScheme {
                Reference = reference
            };

            return(new OpenApiSecurityRequirement {
                { securityScheme, new string[] { } }
            });
        }
Пример #4
0
 /// <summary>
 /// Returns the target of an OpenApiReference from within the workspace.
 /// </summary>
 /// <param name="reference">An instance of an OpenApiReference</param>
 /// <returns></returns>
 public IOpenApiReferenceable ResolveReference(OpenApiReference reference)
 {
     if (_documents.TryGetValue(new Uri(BaseUrl, reference.ExternalResource), out var doc))
     {
         return(doc.ResolveReference(reference, false));
     }
     else if (_fragments.TryGetValue(new Uri(BaseUrl, reference.ExternalResource), out var fragment))
     {
         var jsonPointer = new JsonPointer($"/{reference.Id ?? string.Empty}");
         return(fragment.ResolveReference(jsonPointer));
     }
     return(null);
 }
Пример #5
0
 /// <summary>
 /// Collect external reference
 /// </summary>
 private void AddReference(OpenApiReference reference)
 {
     if (reference != null)
     {
         if (reference.IsExternal)
         {
             if (!_references.ContainsKey(reference.ExternalResource))
             {
                 _references.Add(reference.ExternalResource, reference);
             }
         }
     }
 }
Пример #6
0
        /// <summary>
        /// Compares <see cref="OpenApiReference"/> object.
        /// </summary>
        /// <param name="sourceReference">The source.</param>
        /// <param name="targetReference">The target.</param>
        /// <param name="comparisonContext">The context under which to compare the objects.</param>
        public override void Compare(
            OpenApiReference sourceReference,
            OpenApiReference targetReference,
            ComparisonContext comparisonContext)
        {
            if (sourceReference == null && targetReference == null)
            {
                return;
            }

            if (sourceReference == null || targetReference == null)
            {
                comparisonContext.AddOpenApiDifference(
                    new OpenApiDifference
                {
                    OpenApiDifferenceOperation = OpenApiDifferenceOperation.Update,
                    SourceValue = sourceReference,
                    TargetValue = targetReference,
                    OpenApiComparedElementType = typeof(OpenApiReference),
                    Pointer = comparisonContext.PathString
                });

                return;
            }

            if (sourceReference.Id != targetReference.Id || sourceReference.Type != targetReference.Type)
            {
                WalkAndAddOpenApiDifference(
                    comparisonContext,
                    OpenApiConstants.DollarRef,
                    new OpenApiDifference
                {
                    OpenApiDifferenceOperation = OpenApiDifferenceOperation.Update,
                    SourceValue = sourceReference,
                    TargetValue = targetReference,
                    OpenApiComparedElementType = typeof(OpenApiReference)
                });

                return;
            }

            var source = (T)comparisonContext.SourceDocument.ResolveReference(
                sourceReference);

            var target = (T)comparisonContext.TargetDocument.ResolveReference(
                targetReference);

            comparisonContext
            .GetComparer <T>()
            .Compare(source, target, comparisonContext);
        }
Пример #7
0
 public OpenApiBearerSecurityScheme()
 {
     Description =
         "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"";
     Name      = "Authorization";
     In        = ParameterLocation.Header;
     Type      = SecuritySchemeType.Http;
     Scheme    = "bearer";
     Reference = new OpenApiReference
     {
         Type = ReferenceType.SecurityScheme,
         Id   = "Bearer"
     };
 }
Пример #8
0
        public void SerializeExternalReferenceAsYamlV3Works()
        {
            // Arrange
            var reference = new OpenApiReference {
                ExternalResource = "main.json", Id = "Pets"
            };
            var expected = @"$ref: main.json#/Pets";

            // Act
            var actual = reference.SerializeAsYaml(OpenApiSpecVersion.OpenApi3_0_0);

            // Assert
            actual.Should().Be(expected);
        }
Пример #9
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddTransient <ICalcService, CalcService>();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Calculator API", Version = "v1"
                });

                var reference = new OpenApiReference {
                    Type = ReferenceType.SecurityScheme, Id = CustomAuthExtensions.AuthenticationScheme
                };
                c.AddSecurityDefinition(CustomAuthExtensions.AuthenticationScheme, new OpenApiSecurityScheme
                {
                    Type      = SecuritySchemeType.ApiKey,
                    In        = ParameterLocation.Header,
                    Name      = "Token",
                    Reference = reference
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Name      = CustomAuthExtensions.AuthenticationScheme,
                            Type      = SecuritySchemeType.ApiKey,
                            In        = ParameterLocation.Header,
                            Reference = reference
                        },
                        new List <string>()
                    }
                });
            });

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CustomAuthExtensions.AuthenticationScheme;
                options.DefaultChallengeScheme    = CustomAuthExtensions.AuthenticationScheme;
            }).AddCustomAuth(o => { });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Add", policy => policy.Requirements.Add(new AddPermissionRequirement()));
                options.AddPolicy("Multiplicate", policy => policy.Requirements.Add(new MultiplicatePermissionRequirement()));
            });
            services.AddSingleton <IAuthorizationHandler, PermissionHandler>();
        }
        /// <summary>
        /// Converts <see cref="OpenApiPayloadAttribute"/> to <see cref="OpenApiMediaType"/>.
        /// </summary>
        /// <typeparam name="T">Type of payload attribute inheriting <see cref="OpenApiPayloadAttribute"/>.</typeparam>
        /// <param name="attribute">OpenApi payload attribute.</param>
        /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance to create the JSON schema from .NET Types.</param>
        /// <param name="collection"><see cref="VisitorCollection"/> instance.</param>
        /// <returns><see cref="OpenApiMediaType"/> instance.</returns>
        public static OpenApiMediaType ToOpenApiMediaType <T>(this T attribute, NamingStrategy namingStrategy = null, VisitorCollection collection = null) where T : OpenApiPayloadAttribute
        {
            attribute.ThrowIfNullOrDefault();

            if (namingStrategy.IsNullOrDefault())
            {
                namingStrategy = new DefaultNamingStrategy();
            }

            if (collection.IsNullOrDefault())
            {
                collection = VisitorCollection.CreateInstance();
            }

            var type = attribute.BodyType;

            // Generate schema based on the type.
            var schema = collection.PayloadVisit(type, namingStrategy);

            // Add deprecated attribute.
            if (attribute is OpenApiRequestBodyAttribute)
            {
                schema.Deprecated = (attribute as OpenApiRequestBodyAttribute).Deprecated;
            }
            if (attribute is OpenApiResponseWithBodyAttribute)
            {
                schema.Deprecated = (attribute as OpenApiResponseWithBodyAttribute).Deprecated;
            }

            // For array and dictionary object, the reference has already been added by the visitor.
            if (type.IsReferentialType() && !type.IsOpenApiNullable() && !type.IsOpenApiArray() && !type.IsOpenApiDictionary())
            {
                var reference = new OpenApiReference()
                {
                    Type = ReferenceType.Schema,
                    Id   = attribute.BodyType.GetOpenApiReferenceId(isDictionary: false, isList: false, namingStrategy)
                };

                schema.Reference = reference;
            }

            var mediaType = new OpenApiMediaType()
            {
                Schema = schema
            };

            return(mediaType);
        }
Пример #11
0
        private void InstallSwagger(IServiceCollection services)
        {
            // Register the Swagger Generator as a service. We can define 1 or more Swagger documents here
            services.AddSwaggerGen(x =>
            {
                x.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
                {
                    Title          = "Tweetbook API",
                    Version        = "v1",
                    Description    = "Test documentation for the Tweetbook API",
                    TermsOfService = new System.Uri("https://example.com/terms"),
                    Contact        = new Microsoft.OpenApi.Models.OpenApiContact
                    {
                        Name  = "Alvin Leung",
                        Email = string.Empty,
                        Url   = new System.Uri("https://gooddevbaddev.com"),
                    },
                    License = new Microsoft.OpenApi.Models.OpenApiLicense
                    {
                        Name = "Use under LICX",
                        Url  = new System.Uri("https://example.com/license"),
                    }
                });

                var reference = new OpenApiReference
                {
                    Id   = "Bearer",
                    Type = ReferenceType.SecurityScheme
                };

                var security = new OpenApiSecurityRequirement
                {
                    { new OpenApiSecurityScheme {
                          Reference = reference
                      }, new List <string>() }
                };

                x.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the bearer scheme",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });

                x.AddSecurityRequirement(security);
            });
        }
Пример #12
0
        public void SerializeSchemaReferenceAsYamlV2Works()
        {
            // Arrange
            var reference = new OpenApiReference
            {
                Type = ReferenceType.Schema,
                Id   = "Pet"
            };
            var expected = @"$ref: '#/definitions/Pet'";

            // Act
            var actual = reference.SerializeAsYaml(OpenApiSpecVersion.OpenApi2_0);

            // Assert
            actual.Should().Be(expected);
        }
Пример #13
0
        public static IServiceCollection AddSwaggerConfig(this IServiceCollection services)
        {
            services.AddApiVersioning(options =>
            {
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.DefaultApiVersion = new ApiVersion(1, 0);
                options.ReportApiVersions = true;
            });

            services.AddVersionedApiExplorer(options =>
            {
                options.GroupNameFormat           = "'v'VVV";
                options.SubstituteApiVersionInUrl = true;
            });

            services.AddSwaggerGen(swagger =>
            {
                // swagger.SwaggerDoc("v1", new OpenApiInfo { Title = "My API" });
                swagger.OperationFilter <SwaggerDefaultValues>();

                var securityReference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id   = "Bearer"
                };

                var securityScheme = new OpenApiSecurityScheme
                {
                    Description = "Insira um token JWT desta maneira: Bearer {seu Token} ",
                    Reference   = securityReference,
                    Scheme      = "oauth2",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                };

                var security = new OpenApiSecurityRequirement()
                {
                    { securityScheme, new List <string>() }
                };

                swagger.AddSecurityDefinition("Bearer", securityScheme);

                swagger.AddSecurityRequirement(security);
            });
            return(services);
        }
Пример #14
0
        public void SettingExternalReferenceShouldSucceed(string expected, string externalResource, string id)
        {
            // Arrange & Act
            var reference = new OpenApiReference
            {
                ExternalResource = externalResource,
                Id = id
            };

            // Assert
            reference.ExternalResource.Should().Be(externalResource);
            reference.Type.Should().BeNull();
            reference.Id.Should().Be(id);

            reference.ReferenceV3.Should().Be(expected);
            reference.ReferenceV2.Should().Be(expected);
        }
Пример #15
0
        public ResponseBuilder AddJsonContent <T>()
        {
            var reference = new OpenApiReference();

            var inputType = typeof(T);

            reference.Id = TypeIdentifier.Name(inputType);

            _result.Content.Add("application/json", new OpenApiMediaType()
            {
                Schema = new OpenApiSchema()
                {
                    Reference = reference
                }
            });
            return(this);
        }
Пример #16
0
        /// <inheritdoc />
        public override void Visit(IAcceptor acceptor, KeyValuePair <string, Type> type, NamingStrategy namingStrategy, params Attribute[] attributes)
        {
            var title = type.Value.IsGenericType
                ? namingStrategy.GetPropertyName(type.Value.Name.Split('`').First(), hasSpecifiedName: false) + "_" +
                        string.Join("_",
                                    type.Value.GenericTypeArguments.Select(a => namingStrategy.GetPropertyName(a.Name, false)))
                : namingStrategy.GetPropertyName(type.Value.Name, hasSpecifiedName: false);
            var name = this.Visit(acceptor, name: type.Key, title: title, dataType: "object", dataFormat: null, attributes: attributes);

            if (name.IsNullOrWhiteSpace())
            {
                return;
            }

            if (!this.IsNavigatable(type.Value))
            {
                return;
            }

            var instance = acceptor as OpenApiSchemaAcceptor;

            if (instance.IsNullOrDefault())
            {
                return;
            }

            // Processes properties.
            var properties = type.Value
                             .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                             .Where(p => !p.ExistsCustomAttribute <JsonIgnoreAttribute>())
                             .ToDictionary(p => p.GetJsonPropertyName(namingStrategy), p => p);

            this.ProcessProperties(instance, name, properties, namingStrategy);

            // Adds the reference.
            var reference = new OpenApiReference()
            {
                Type = ReferenceType.Schema,
                Id   = type.Value.GetOpenApiReferenceId(isDictionary: false, isList: false, namingStrategy)
            };

            instance.Schemas[name].Reference = reference;

            instance.Schemas[name].Example = this.GetExample(type.Value, namingStrategy);
        }
Пример #17
0
        public void SerializeSchemaReferenceAsJsonV2Works()
        {
            // Arrange
            var reference = new OpenApiReference
            {
                Type = ReferenceType.Schema,
                Id   = "Pet"
            };

            var expected = @"{
  ""$ref"": ""#/definitions/Pet""
}".MakeLineBreaksEnvironmentNeutral();

            // Act
            var actual = reference.SerializeAsJson(OpenApiSpecVersion.OpenApi2_0);

            // Assert
            actual.MakeLineBreaksEnvironmentNeutral().Should().Be(expected);
        }
Пример #18
0
    private OAReference CreateReference(OpenApiReference openApiReference)
    {
        if (openApiReference == null)
        {
            return(new OAReference());
        }

        return(new OAReference()
        {
            IsPresent = true,
            ExternalResource = openApiReference.ExternalResource,
            Type = (OAReferenceType)openApiReference.Type,
            Id = openApiReference.Id,
            IsExternal = openApiReference.IsExternal,
            IsLocal = openApiReference.IsLocal,
            Reference = string.IsNullOrEmpty(openApiReference.ReferenceV2)
            ? openApiReference.ReferenceV3 : openApiReference.ReferenceV2,
        });
    }
Пример #19
0
        public void LoadParameterReference()
        {
            // Arrange
            var      context    = new ParsingContext();
            var      diagnostic = new OpenApiDiagnostic();
            RootNode rootNode;

            using (var stream = File.OpenRead(Path.Combine(SampleFolderPath, "multipleReferences.v2.yaml")))
            {
                var yamlStream = new YamlStream();
                yamlStream.Load(new StreamReader(stream));
                var yamlDocument = yamlStream.Documents.First();

                rootNode = new RootNode(context, diagnostic, yamlDocument);
            }

            context.ReferenceService = new OpenApiV2ReferenceService(rootNode);

            var reference = new OpenApiReference
            {
                Type = ReferenceType.Parameter,
                Id   = "skipParam"
            };

            // Act
            context.ReferenceService.TryLoadReference(reference, out var referencedObject);

            // Assert
            referencedObject.ShouldBeEquivalentTo(
                new OpenApiParameter
            {
                Name        = "skip",
                In          = ParameterLocation.Query,
                Description = "number of items to skip",
                Required    = true,
                Schema      = new OpenApiSchema
                {
                    Type   = "integer",
                    Format = "int32"
                }
            }
                );
        }
Пример #20
0
        public void SerializeSchemaReferenceAsJsonV3Works()
        {
            // Arrange
            var reference = new OpenApiReference {
                Type = ReferenceType.Schema, Id = "Pet"
            };
            var expected = @"{
  ""$ref"": ""#/components/schemas/Pet""
}";

            // Act
            var actual = reference.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0_0);

            expected = expected.MakeLineBreaksEnvironmentNeutral();
            actual   = actual.MakeLineBreaksEnvironmentNeutral();

            // Assert
            actual.Should().Be(expected);
        }
        private T ResolveReference<T>(OpenApiReference reference) where T : class, IOpenApiReferenceable, new()
        {
            if (string.IsNullOrEmpty(reference.ExternalResource))
            {
                try
                {
                    return _currentDocument.ResolveReference(reference) as T;
                }
                catch (OpenApiException ex)
                {
                    _errors.Add(new OpenApiReferenceError(ex));
                    return null;
                }
            }
            else if (_resolveRemoteReferences == true)
            {
                if (_currentDocument.Workspace == null)
                {
                    _errors.Add(new OpenApiReferenceError(reference,"Cannot resolve external references for documents not in workspaces."));
                    // Leave as unresolved reference
                    return new T()
                    {
                        UnresolvedReference = true,
                        Reference = reference
                    };
                }
                var target = _currentDocument.Workspace.ResolveReference(reference);

                // TODO:  If it is a document fragment, then we should resolve it within the current context

                return target as T;
            }
            else
            {
                // Leave as unresolved reference
                return new T()
                {
                    UnresolvedReference = true,
                    Reference = reference
                };
            }
        }
        // Register the Swagger generator, defining 1 or more Swagger documents
        // Config Authorization
        public static IServiceCollection AddSwaggerDocumentation(this IServiceCollection services)
        {
            services.AddSwaggerGen(config =>
            {
                config.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title       = "Stock Market Service API",
                    Version     = "v1",
                    Description = "Stock market service API in Asp.net Core"
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                config.IncludeXmlComments(xmlPath);

                OpenApiSecurityScheme openApiSecurityScheme = new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                };
                config.AddSecurityDefinition("Bearer", openApiSecurityScheme);

                OpenApiReference apiReference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id   = "Bearer"
                };
                OpenApiSecurityScheme apiSecurityScheme = new OpenApiSecurityScheme
                {
                    Reference = apiReference
                };
                OpenApiSecurityRequirement apiSecurityRequirement = new OpenApiSecurityRequirement
                {
                    { apiSecurityScheme, new string[] { } }
                };
                config.AddSecurityRequirement(apiSecurityRequirement);
            });

            return(services);
        }
Пример #23
0
        /// <summary>
        /// Converts <see cref="OpenApiPayloadAttribute"/> to <see cref="OpenApiMediaType"/>.
        /// </summary>
        /// <typeparam name="T">Type of payload attribute inheriting <see cref="OpenApiPayloadAttribute"/>.</typeparam>
        /// <param name="attribute">OpenApi payload attribute.</param>
        /// <returns><see cref="OpenApiMediaType"/> instance.</returns>
        public static OpenApiMediaType ToOpenApiMediaType <T>(this T attribute) where T : OpenApiPayloadAttribute
        {
            attribute.ThrowIfNullOrDefault();

            var reference = new OpenApiReference()
            {
                Type = ReferenceType.Schema,
                Id   = attribute.BodyType.Name
            };
            var schema = new OpenApiSchema()
            {
                Reference = reference
            };
            var mediaType = new OpenApiMediaType()
            {
                Schema = schema
            };

            return(mediaType);
        }
Пример #24
0
        public void SettingInternalReferenceForComponentsStyleReferenceShouldSucceed(
            string input,
            ReferenceType type,
            string id)
        {
            // Arrange & Act
            var reference = new OpenApiReference
            {
                Type = type,
                Id   = id
            };

            // Assert
            reference.ExternalResource.Should().BeNull();
            reference.Type.Should().Be(type);
            reference.Id.Should().Be(id);

            reference.ReferenceV3.Should().Be(input);
            reference.ReferenceV2.Should().Be(input.Replace("schemas", "definitions").Replace("/components", ""));
        }
Пример #25
0
        public void SerializeExternalReferenceAsJsonV3Works()
        {
            // Arrange
            var reference = new OpenApiReference {
                ExternalResource = "main.json", Id = "Pets"
            };

            var expected = @"{
  ""$ref"": ""main.json#/Pets""
}";

            // Act
            var actual = reference.SerializeAsJson(OpenApiSpecVersion.OpenApi3_0_0);

            expected = expected.MakeLineBreaksEnvironmentNeutral();
            actual   = actual.MakeLineBreaksEnvironmentNeutral();

            // Assert
            actual.Should().Be(expected);
        }
        public void LoadParameterReference()
        {
            // Arrange
            OpenApiDocument document;
            var             diagnostic = new OpenApiDiagnostic();

            using (var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "multipleReferences.v2.yaml")))
            {
                document = new OpenApiStreamReader().Read(stream, out diagnostic);
            }

            var reference = new OpenApiReference
            {
                Type = ReferenceType.Parameter,
                Id   = "skipParam"
            };

            // Act
            var referencedObject = document.ResolveReference(reference);

            // Assert
            referencedObject.ShouldBeEquivalentTo(
                new OpenApiParameter
            {
                Name        = "skip",
                In          = ParameterLocation.Query,
                Description = "number of items to skip",
                Required    = true,
                Schema      = new OpenApiSchema
                {
                    Type   = "integer",
                    Format = "int32"
                },
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.Parameter,
                    Id   = "skipParam"
                }
            }
                );
        }
Пример #27
0
        /// <inheritdoc />
        public override OpenApiSchema PayloadVisit(Type type, NamingStrategy namingStrategy)
        {
            var schema = this.PayloadVisit(dataType: "object", dataFormat: null);

            // Gets the schema for the underlying type.
            var underlyingType = type.GetGenericArguments()[1];
            var properties     = this.VisitorCollection.PayloadVisit(underlyingType, namingStrategy);

            // Adds the reference to the schema for the underlying type.
            var reference = new OpenApiReference()
            {
                Type = ReferenceType.Schema,
                Id   = underlyingType.GetOpenApiReferenceId(isDictionary: false, isList: false, namingStrategy)
            };

            properties.Reference = reference;

            schema.AdditionalProperties = properties;

            return(schema);
        }
        /// <inheritdoc />
        public override OpenApiSchema PayloadVisit(Type type, NamingStrategy namingStrategy)
        {
            var schema = this.PayloadVisit(dataType: "array", dataFormat: null);

            // Gets the schema for the underlying type.
            var underlyingType = type.GetElementType() ?? type.GetGenericArguments()[0];
            var items          = this.VisitorCollection.PayloadVisit(underlyingType, namingStrategy);

            // Adds the reference to the schema for the underlying type.
            var reference = new OpenApiReference()
            {
                Type = ReferenceType.Schema,
                Id   = underlyingType.GetOpenApiReferenceId(isDictionary: false, isList: false, namingStrategy)
            };

            items.Reference = reference;

            schema.Items = items;

            return(schema);
        }
Пример #29
0
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            context.SchemaGenerator.GenerateSchema(typeof(CustomExceptionDto), context.SchemaRepository);

            OpenApiReference reference = new OpenApiReference {
                Id = nameof(CustomExceptionDto), Type = ReferenceType.Schema
            };
            OpenApiSchema schema = new OpenApiSchema {
                Reference = reference
            };
            OpenApiMediaType mediaType = new OpenApiMediaType {
                Schema = schema
            };
            Dictionary <string, OpenApiMediaType> content = new Dictionary <string, OpenApiMediaType> {
                { "application/json", mediaType }
            };

            operation.Responses.Add("400", new OpenApiResponse {
                Description = "Bad Request", Content = content
            });
            operation.Responses.Add("500", new OpenApiResponse {
                Description = "Internal Server Error", Content = content
            });

            bool?haveAuth = context.MethodInfo?.DeclaringType?
                            .GetCustomAttributes(true)
                            .Union(context.MethodInfo?.GetCustomAttributes(true))
                            .OfType <AuthorizeAttribute>()
                            .Any();

            if (haveAuth != true)
            {
                return;
            }

            operation.Responses.Add("401", new OpenApiResponse {
                Description = "Unauthorized", Content = content
            });
        }
        /// <summary>
        /// Adds project swagger
        /// </summary>
        public static IServiceCollection AddProjectSwagger(this IServiceCollection services)
        {
            return(services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "WebApi", Version = "v1"
                });
                options.DocInclusionPredicate((docName, description) => true);

                // Send description to front with love :)
                options.IncludeXmlComments(Path.ChangeExtension(typeof(Startup).Assembly.Location, ".xml"));
                options.IncludeXmlComments(Path.ChangeExtension(typeof(UserDto).Assembly.Location, ".xml"));

                // Add jwt auth to swagger
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Fill input: bearer {token}",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey
                });

                var oaReference = new OpenApiReference()
                {
                    Id = "Bearer",
                    Type = ReferenceType.SecurityScheme
                };

                var securityScheme = new OpenApiSecurityScheme {
                    Reference = oaReference
                };
                var security = new OpenApiSecurityRequirement
                {
                    { securityScheme, Array.Empty <string>() }
                };
                options.AddSecurityRequirement(security);
            }));
        }