Пример #1
0
        public static IServiceCollection ArkConfigureSwaggerAuth0(this IServiceCollection services, string domain, string audience, string clientId)
        {
            services.ConfigureSwaggerGen(c =>
            {
                var oauthScheme = new OAuth2Scheme
                {
                    Type             = "oauth2",
                    Flow             = "implicit",
                    AuthorizationUrl = $"https://{domain}/authorize",
                    Scopes           = new Dictionary <string, string>
                    {
                        { "openid profile email", "Grant access to user" }
                    }
                };
                c.AddSecurityDefinition("oauth2", oauthScheme);
            });

            services.ArkConfigureSwaggerUI(c =>
            {
                c.OAuthClientId(clientId);
                c.OAuthAppName("WebApi");
                c.OAuthAdditionalQueryStringParams(new Dictionary <string, string>()
                {
                    { "audience", audience }
                });
            });

            return(services);
        }
Пример #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddAuthorization(config =>
            {
                config.AddPolicy("can-update", p => p.RequireClaim("scopes", "api:update"));
                config.AddPolicy("can-delete", p => p.RequireClaim("scopes", "api:delete"));
            })
            .AddScoped <IHttpContextAccessor, HttpContextAccessor>()
            .AddSwaggerGen(options =>
            {
                options.SwaggerDoc(
                    "1.0",
                    new Info
                {
                    Version = "1.0"
                });

                // configure authentication for Swagger schema -
                // which endpoints to display in Swagger UI for specified auth token
                var schema = new OAuth2Scheme
                {
                    Type        = "apiKey",
                    Description = "JWT token based authorization"
                };
                schema.Extensions.Add("in", "header");
                schema.Extensions.Add("name", "Authorization");
                options.AddSecurityDefinition("api_key", schema);

                // filter non-authorized endpoints
                options.DocumentFilter <SwaggerAuthorizationFilter>();
            });
            services.AddMvc();
        }
Пример #3
0
        public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            JsonSerializer serializer)
        {
            JObject        jsonObject = JObject.Load(reader);
            SecurityScheme scheme     = null;
            string         type       = jsonObject["type"].ToString();

            switch (type)
            {
            case "apiKey":
                scheme = new ApiKeyScheme();
                break;

            case "oauth2":
                scheme = new OAuth2Scheme();
                break;

            case "basic":
                scheme = new BasicAuthScheme();
                break;

            default:
                throw new ArgumentException($"Unexpected security scheme '{type}'");
            }

            serializer.Populate(jsonObject.CreateReader(), scheme);
            return(scheme);
        }
Пример #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // ReSharper disable once UnusedMember.Global
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            var appSettings = this.AppSettings;

            services.AddSwaggerGen(
                c =>
            {
                c.SwaggerDoc("v1", new Info()
                {
                    Title = "Arcadian-Assistant API", Version = "v1"
                });

                var scheme  = new OAuth2Scheme();
                scheme.Flow = "implicit";

                scheme.AuthorizationUrl = appSettings.Security.AuthorizationUrl;
                scheme.TokenUrl         = appSettings.Security.TokenUrl;

                c.AddSecurityDefinition("oauth2", scheme);
            });

            services.ConfigureSwaggerGen(
                x =>
            {
                x.DescribeAllEnumsAsStrings();
                //x.CustomSchemaIds(t => t.FullName);
            });

            services.AddScoped <AuthenticationEvents>();

            services
            .AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; })
            .AddJwtBearer(
                jwtOptions =>
            {
                jwtOptions.Audience        = appSettings.Security.ClientId;
                jwtOptions.MetadataAddress = appSettings.Security.OpenIdConfigurationUrl;
                jwtOptions.Events          = new JwtEventsHandler();
            })
            .AddBasicAuthentication(
                basicOptions =>
            {
                basicOptions.Realm      = this.AppSettings.ServiceEndpointsAuthentication.Realm;
                basicOptions.EventsType = typeof(AuthenticationEvents);
            });

            services
            .AddAuthorization(options =>
            {
                options.AddPolicy(Policies.UserIsEmployee, policy => policy.Requirements.Add(new UserIsEmployeeRequirement()));

                options.AddPolicy(Policies.ServiceEndpoint, policy =>
                {
                    policy.AddAuthenticationSchemes(BasicAuthenticationDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme);
                    policy.RequireAuthenticatedUser();
                });
            });
        }
Пример #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = "https://localhost:5000";
                options.RequireHttpsMetadata = false;
                options.ApiName = "course-api";
            });

            // Register the Swagger generator, defining one or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Course API", Version = "v1"
                });
                var section     = Configuration.GetSection("Identity:Swagger");
                var oauthScheme = new OAuth2Scheme();
                oauthScheme.AuthorizationUrl = $"{section["Authority"]}/connect/authorize";
                oauthScheme.TokenUrl         = $"{section["Authority"]}/connect/token";
                oauthScheme.Flow             = section["Flow"];
                var scopes = new Dictionary <string, string>();
                section.GetSection("Scopes").Bind(scopes);
                oauthScheme.Scopes = scopes;
                c.AddSecurityDefinition("Bearer", oauthScheme);
            });
            services.AddAuthorization(options =>
            {
                var section = Configuration.GetSection("Identity:Authorization");
                Dictionary <string, string[]> policies = new Dictionary <string, string[]>();
                section.Bind(policies);
                foreach (var policy in policies)
                {
                    options.AddPolicy(policy.Key, p =>
                    {
                        p.RequireRole(policy.Value);
                    });
                }
            });
        }
Пример #6
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(redisConfiguration);
            services.AddSingleton(urlBuilderConfiguration);
            services.AddSingleton(databaseConfiguration);

            // ** Authentication ** //
            services.AddAuthentication("Bearer")
            .AddJwtBearer(options =>
            {
                options.Authority = urlBuilderConfiguration.Auth.Url;
                options.Audience  = "wpc-netflix-apis";
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                };

                if (this.environment.IsDevelopment())
                {
                    options.RequireHttpsMetadata = false;
                }
            });

            services.AddMongoDb();

            services
            .AddDataProtection()
            .SetApplicationName("wpc-netflix")
            .PersistKeysToRedis(redisConfiguration.Connection, "my-dataProtection-keys");

            services.AddDistributedRedisCache(options =>
            {
                options.Configuration = this.redisConfiguration.ConfigurationOptions.ToString();
            });

            // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service
            // note: the specified format code will format the version as "'v'major[.minor][-status]"
            services
            .AddMvcCore()
            .AddVersionedApiExplorer(o => o.GroupNameFormat = "'v'VVV");

            services.AddMvc();
            services.AddApiVersioning(o => o.ReportApiVersions = true);

            if (!this.environment.IsProduction())
            {
                services.AddSwaggerGen(
                    options =>
                {
                    // resolve the IApiVersionDescriptionProvider service
                    // note: that we have to build a temporary service provider here because one has not been created yet
                    var provider = services.BuildServiceProvider().GetRequiredService <IApiVersionDescriptionProvider>();

                    // add a swagger document for each discovered API version
                    // note: you might choose to skip or document deprecated API versions differently
                    foreach (var description in provider.ApiVersionDescriptions)
                    {
                        options.SwaggerDoc(description.GroupName, SwaggerHelper.CreateInfoForApiVersion(description));
                    }

                    // add a custom operation filter which sets default values
                    options.OperationFilter <SwaggerDefaultValues>();

                    ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

                    // integrate xml comments
                    // options.IncludeXmlComments(SwaggerHelper.XmlCommentsFilePath);

                    // Authorization API documentation
                    options.OperationFilter <AuthResponsesOperationFilter>();
                    options.OperationFilter <BadRequestResponseOperationFilter>();
                    options.OperationFilter <TagByApiExplorerSettingsOperationFilter>();

                    // Authentication
                    var oAuth2Scheme = new OAuth2Scheme();
                    oAuth2Scheme.AuthorizationUrl = urlBuilderConfiguration.Auth.Url + "/connect/authorize";
                    oAuth2Scheme.Flow             = "implicit";
                    oAuth2Scheme.TokenUrl         = urlBuilderConfiguration.Auth.Url + "/connect/authorize";
                    oAuth2Scheme.Scopes           = new ConcurrentDictionary <string, string>();
                    oAuth2Scheme.Scopes.Add(new KeyValuePair <string, string>("admin", "Admin APIs access."));
                    oAuth2Scheme.Scopes.Add(new KeyValuePair <string, string>("www", "Www APIs access."));

                    options.AddSecurityDefinition("Bearer", oAuth2Scheme);
                });
            }
        }
Пример #7
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">The services.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(typeof(MainProfile), typeof(ChatProfile));

            services.AddSwaggerGen(x =>
            {
                x.SwaggerDoc("v1", new Info {
                    Version = "v1", Title = "Football API"
                });

                var oauthScheme = new OAuth2Scheme
                {
                    Description =
                        "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    TokenUrl = "/token",
                    Flow     = "password"
                };

                x.AddSecurityDefinition("oauth2", oauthScheme);
                x.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                    { "oauth2", new string[] { } }
                });

                IncludeComments(x);
            });

            services.AddDbContext <FootballContext>(
                opt =>
            {
                opt.UseLazyLoadingProxies();
                opt.UseSqlServer(this.Configuration.GetConnectionString("SqlConnection"));
            },
                contextLifetime: ServiceLifetime.Scoped,
                optionsLifetime: ServiceLifetime.Scoped);

            // Data
            services.AddScoped <IPlayerRepository, PlayerRepository>();
            services.AddScoped <IPlayerActivationRepository, PlayerActivationRepository>();
            services.AddScoped <IRefreshTokenRepository, RefreshTokenRepository>();
            services.AddScoped <IGameRepository, GameRepository>();
            services.AddScoped <IMeetingTimeRepository, MeetingTimeRepository>();
            services.AddScoped <IFriendshipRepository, FriendshipRepository>();
            services.AddChatRepository();

            // Services
            services.AddTokenConfiguration(this.TokenConfiguration);
            services.AddSmtpClient();
            services.AddScoped <INotificationService, EmailService>();
            services.AddScoped <IRegisterNotifier, RegisterNotifier>();
            services.AddSingleton(this.TokenConfiguration);
            services.AddScoped <IIdentityService, IdentityService>();
            services.AddScoped <IGameService, GameService>();
            services.AddScoped <IPlayerService, PlayerService>();
            services.AddScoped <IRegistrationService, RegistrationService>();

            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(ValidationModelAttribute));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddCors();

            services.AddSignalR()
            .AddHubOptions <ChatHub>(options => options.EnableDetailedErrors = true);
        }