Example #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddAuth(this IServiceCollection services, IConfiguration configuration)
        {
            var openIdOptions = new OpenIdOptions();

            configuration.GetSection(nameof(OpenIdOptions)).Bind(openIdOptions);

            // configure jwt authentication
            var key = Encoding.ASCII.GetBytes(openIdOptions.ClientSecret);

            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddCookie("MyCookie", options =>
            {
                options.ExpireTimeSpan = TimeSpan.FromSeconds(openIdOptions.AccessTokenSecondsLifetime);
            })
            .AddJwtBearer(options =>
            {
                options.Authority            = openIdOptions.Authority;
                options.Audience             = openIdOptions.Audience;
                options.RequireHttpsMetadata = openIdOptions.RequireHttpsMetadata;
                options.SaveToken            = true;
                //GetClaimsFromUserInfoEndpoint = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // Validate Authority
                    ValidateIssuer           = true,
                    ValidIssuer              = openIdOptions.Authority,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),

                    ValidateAudience = true,
                    ValidAudience    = openIdOptions.Audience,

                    ValidateLifetime = true,
                    ClockSkew        = TimeSpan.Zero
                };
            });

            return(services);
        }
Example #2
0
        /// <summary>
        /// Configurar servicios
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddOpenApi(this IServiceCollection services, IConfiguration configuration)
        {
            var openApiOptions = new OpenApiOptions();

            configuration.GetSection(nameof(OpenApiOptions)).Bind(openApiOptions);

            services.AddSwaggerGenNewtonsoftSupport();

            services.AddFluentValidationRulesToSwagger();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = openApiOptions.Title, Version = "v1"
                });

                // Set the comments path for the Swagger JSON and UI.
                string xmlPath = null;
                if (!string.IsNullOrWhiteSpace(openApiOptions.XmlDocumentationFile))
                {
                    xmlPath = Path.Combine(AppContext.BaseDirectory, openApiOptions.XmlDocumentationFile);
                    c.IncludeXmlComments(xmlPath);
                }

                var openIdOptions = new OpenIdOptions();
                configuration.GetSection(nameof(OpenIdOptions)).Bind(openIdOptions);

                if (!string.IsNullOrWhiteSpace(openIdOptions.Authority))
                {
                    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                    {
                        Type  = SecuritySchemeType.OAuth2,
                        Flows = new OpenApiOAuthFlows
                        {
                            Password = new OpenApiOAuthFlow
                            {
                                AuthorizationUrl = new Uri(openIdOptions.Authority),
                                TokenUrl         = new Uri(openIdOptions.Authority + "/connect/token"),
                                Scopes           = new Dictionary <string, string> {
                                    { openIdOptions.Scope, "Scope" }
                                }
                            }
                        }
                    });

                    c.AddSecurityRequirement(new OpenApiSecurityRequirement
                    {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference {
                                    Type = ReferenceType.SecurityScheme, Id = "oauth2"
                                }
                            },
                            new[] { openIdOptions.Audience }
                        }
                    });
                }


                c.AddEnumsWithValuesFixFilters(services, o =>
                {
                    // add schema filter to fix enums (add 'x-enumNames' for NSwag) in schema
                    o.ApplySchemaFilter = true;

                    // add parameter filter to fix enums (add 'x-enumNames' for NSwag) in schema parameters
                    o.ApplyParameterFilter = true;

                    // add document filter to fix enums displaying in swagger document
                    o.ApplyDocumentFilter = true;

                    // add descriptions from DescriptionAttribute or xml-comments to fix enums (add 'x-enumDescriptions' for schema extensions) for applied filters
                    o.IncludeDescriptions = true;

                    // get descriptions from DescriptionAttribute then from xml-comments
                    o.DescriptionSource = DescriptionSources.DescriptionAttributesThenXmlComments;

                    // get descriptions from xml-file comments on the specified path
                    // should use "options.IncludeXmlComments(xmlFilePath);" before
                    if (!string.IsNullOrWhiteSpace(xmlPath))
                    {
                        o.IncludeXmlCommentsFrom(xmlPath);
                    }
                    // the same for another xml-files...
                });



                //c.OperationFilter<RemoveVersionFromParameter>();
                //c.DocumentFilter<ReplaceVersionWithExactValueInPath>();
                c.OperationFilter <SecurityRequirementsOperationFilter>();
                //c.OperationFilter<FileOperation>();

                // remove Paths and Defenitions from OpenApi documentation without accepted roles
                // c.DocumentFilter<HidePathsAndDefinitionsByRolesDocumentFilter>(new List<string> { "AcceptedRole" });
            });

            return(services);
        }