示例#1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // Configuration options
            services.AddOptions();
            services.Configure <EndpointOption>(Configuration.GetSection("Endpoints"));
            services.Configure <IndicesOption>(Configuration.GetSection("ElasticsearchIndices"));

            // Add framework services
            services.AddMvc();

            // Inject an implementation of ISwaggerProvider with defaulted settings applied
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Title   = "Vokabular FulltextService API",
                    Version = "v1",
                });
                options.DescribeAllEnumsAsStrings();
                options.IncludeXmlComments(ServiceUtils.GetAppXmlDocumentationPath());
                options.IncludeXmlComments(ServiceUtils.GetAppXmlDocumentationPath(typeof(FulltextSearchCorpusResultContract)));

                options.DocumentFilter <PolymorphismDocumentFilter <SearchCriteriaContract> >();
                options.SchemaFilter <PolymorphismSchemaFilter <SearchCriteriaContract> >();
            });

            // AutoMapper
            services.AddAutoMapper();

            // IoC
            var container = new DryIocContainerWrapper();

            container.Install <FulltextServiceContainerRegistration>();
            Container = container;

            return(container.CreateServiceProvider(services));
        }
示例#2
0
文件: Startup.cs 项目: RIDICS/ITJakub
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //IdentityModelEventSource.ShowPII = true; // Enable to debug authentication problems

            var openIdConnectConfig    = Configuration.GetSection("OpenIdConnect").Get <OpenIdConnectConfiguration>();
            var portalConfig           = Configuration.GetSection("PortalConfig").Get <PortalOption>();
            var endpointsConfiguration = Configuration.GetSection("Endpoints").Get <EndpointOption>();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.ExpireTimeSpan   = m_cookieExpireTimeSpan;
                options.Cookie.Name      = $"identity{portalConfig.PortalType}";
                options.AccessDeniedPath = "/Error/403/";
                options.LoginPath        = "/Account/Login";
            })
            .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
            {
                options.Authority    = openIdConnectConfig.Url;
                options.ClientSecret = openIdConnectConfig.ClientSecret;
                options.ClientId     = openIdConnectConfig.ClientId;

                options.ResponseType = "code id_token";

                options.Scope.Clear();
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("offline_access");
                options.Scope.Add("auth_api.Internal");

                options.ClaimActions.MapJsonKey(ClaimTypes.Role, "role");
                options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
                options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
                options.ClaimActions.MapJsonKey(ClaimTypes.GivenName, "given_name");
                options.ClaimActions.MapJsonKey(ClaimTypes.Surname, "family_name");
                options.ClaimActions.MapJsonKey(CustomClaimTypes.EmailConfirmed, "email_confirmed");
                options.ClaimActions.MapJsonKey(CustomClaimTypes.Permission, CustomClaimTypes.Permission);
                options.ClaimActions.MapJsonKey(CustomClaimTypes.ResourcePermission, CustomClaimTypes.ResourcePermission);
                options.ClaimActions.MapJsonKey(CustomClaimTypes.ResourcePermissionType, CustomClaimTypes.ResourcePermissionType);

                options.GetClaimsFromUserInfoEndpoint = true;
                options.SaveTokens = true;

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = ClaimTypes.Name,
                    RoleClaimType = ClaimTypes.Role
                };

                //Adds return url address in case of user clicking on "Leave" button on login page
                options.Events = new OpenIdConnectEvents
                {
                    OnRedirectToIdentityProvider = context =>
                    {
                        var returnUrl = context.Request.GetAppBaseUrl();
                        context.ProtocolMessage.SetParameter("returnUrlOnCancel", returnUrl.ToString());

                        var culture = context.HttpContext.RequestServices.GetRequiredService <ILocalizationService>()
                                      .GetRequestCulture();
                        context.ProtocolMessage.SetParameter("culture", culture.Name);

                        return(Task.CompletedTask);
                    },
                    OnRedirectToIdentityProviderForSignOut = context =>
                    {
                        var culture = context.HttpContext.RequestServices.GetRequiredService <ILocalizationService>()
                                      .GetRequestCulture();
                        context.ProtocolMessage.SetParameter("culture", culture.Name);

                        return(Task.CompletedTask);
                    },
                    OnUserInformationReceived = context =>
                    {
                        var communicationProvider = context.HttpContext.RequestServices.GetRequiredService <CommunicationProvider>();
                        var client = communicationProvider.GetMainServiceUserClient();

                        client.CreateUserIfNotExist(new CreateUserIfNotExistContract
                        {
                            ExternalId = context.Principal.GetIdOrDefault().GetValueOrDefault(),
                            Username   = GetUserValueByClaim(context, ClaimTypes.Name),
                            FirstName  = GetUserValueByClaim(context, ClaimTypes.GivenName),
                            LastName   = GetUserValueByClaim(context, ClaimTypes.Surname),
                        });

                        return(Task.CompletedTask);
                    },
                };
            });

            services.AddSingleton <IAuthorizationPolicyProvider, AuthorizationPolicyProvider>();

            //store claims in memory:
            services.SetAuthenticationTicketStore <MemoryCacheTicketStore>(new CacheTicketStoreConfig
            {
                SlidingExpiration = m_cookieExpireTimeSpan
            });
            services.RegisterAutomaticTokenManagement();

            // Register Auth service client, because contains components for obtaining access token (for user and also for app)
            services.RegisterAuthorizationHttpClientComponents <AuthServiceClientLocalization>(new AuthServiceCommunicationConfiguration
            {
                TokenName      = null, // not required
                ApiAccessToken = null, // not required
                AuthenticationServiceAddress = openIdConnectConfig.Url,
            }, new OpenIdConnectConfig
            {
                Url    = openIdConnectConfig.Url,
                Scopes = new List <string> {
                    openIdConnectConfig.AuthServiceScopeName
                },
                ClientId     = openIdConnectConfig.ClientId,
                ClientSecret = openIdConnectConfig.ClientSecret,
            }, new AuthServiceControllerBasePathsConfiguration(/*Not required to fill because client is not used*/));

            services.RegisterMainServiceClientComponents <AuthTokenProvider, MainServiceClientLocalization>(new MainServiceClientConfiguration
            {
                PortalType          = (PortalTypeContract)portalConfig.PortalType,
                Url                 = new Uri(endpointsConfiguration.Addresses["MainService"]),
                CreateCustomHandler = false
            });

            // Configuration options
            services.AddOptions();
            services.AddSingleton(openIdConnectConfig);
            services.Configure <EndpointOption>(Configuration.GetSection("Endpoints"));
            services.Configure <GoogleCalendarConfiguration>(Configuration.GetSection("GoogleCalendar"));
            services.Configure <FormOptions>(options => { options.MultipartBodyLengthLimit = 1048576000; });
            services.Configure <PortalOption>(Configuration.GetSection("PortalConfig"));
            services.Configure <AutoLoginCookieConfiguration>(Configuration.GetSection("AutoLoginCookie"));
            services.Configure <ForumOption>(Configuration.GetSection("ForumOptions")); // The same config as Vokabular.ForumSite.Core.Options.ForumOption
            services.PostConfigure <AutoLoginCookieConfiguration>(config =>
            {
                config.CookieName = $"{AutoLoginCookieConfiguration.CookieNamePrefix}{portalConfig.PortalType}";
            });

            // Localization
            var localizationConfiguration = Configuration.GetSection("Localization").Get <LocalizationConfiguration>();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddLocalizationService(localizationConfiguration, new NHibernateDatabaseConfiguration());

            // Core configuration
            services.AddAutoMapper();
            services.AddMvc()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    return(factory
                           .Create(type.Name, LocTranslationSource.File.ToString()));
                };
            });

            // IoC
            var container = new DryIocContainerWrapper();

            container.RegisterLogger();
            container.Install <WebHubContainerRegistration>();
            container.Install <NHibernateInstaller>();
            Container = container;


            return(container.CreateServiceProvider(services));
        }
示例#3
0
文件: Startup.cs 项目: RIDICS/ITJakub
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var openIdConnectConfig      = Configuration.GetSection("OpenIdConnect").Get <OpenIdConnectConfiguration>();
            var endpointsConfiguration   = Configuration.GetSection("Endpoints").Get <EndpointOption>();
            var credentialsConfiguration = Configuration.GetSection("Credentials").Get <List <CredentialsOption> >();

            // Configuration options
            services.AddOptions();
            services.Configure <EndpointOption>(Configuration.GetSection("Endpoints"));
            services.Configure <List <CredentialsOption> >(Configuration.GetSection("Credentials"));
            services.Configure <PathConfiguration>(Configuration.GetSection("PathConfiguration"));
            services.Configure <OaiPmhClientOption>(Configuration.GetSection("OaiPmhClientOption"));
            services.Configure <ForumOption>(Configuration.GetSection("ForumOptions"));
            services.Configure <RegistrationOption>(Configuration.GetSection("RegistrationOption"));

            services.Configure <FormOptions>(options => { options.MultipartBodyLengthLimit = 1048576000; });

            // Add framework services.
            services.AddMvc()
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <MainServiceCoreContainerRegistration>());
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // Inject an implementation of ISwaggerProvider with defaulted settings applied
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Title   = "Vokabular MainService API",
                    Version = "v1",
                });
                options.DescribeAllEnumsAsStrings();
                options.IncludeXmlComments(ServiceUtils.GetAppXmlDocumentationPath());
                options.IncludeXmlComments(ServiceUtils.GetAppXmlDocumentationPath(typeof(BookContract)));
                options.OperationFilter <AddResponseHeadersFilter>();
                options.OperationFilter <FileOperationFilter>();
                options.OperationFilter <AddGlobalHeaderFilter>(new GlobalHeaderValues
                {
                    Name         = MainServiceHeaders.PortalTypeHeader,
                    Values       = Enum.GetNames(typeof(PortalTypeContract)).ToList <object>(),
                    DefaultValue = PortalTypeContract.Research.ToString(),
                });

                options.DocumentFilter <PolymorphismDocumentFilter <SearchCriteriaContract> >();
                options.SchemaFilter <PolymorphismSchemaFilter <SearchCriteriaContract> >();

                options.AddSecurityDefinition("implicit-oauth2", new OAuth2Scheme
                {
                    Flow             = "implicit",
                    AuthorizationUrl = $"{openIdConnectConfig.Url}connect/authorize",
                    TokenUrl         = $"{openIdConnectConfig.Url}connect/token",
                    Scopes           = new Dictionary <string, string> {
                        { "auth_api.Internal", "API - internal" },
                    }
                });

                options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    { "implicit-oauth2", new[] { "auth_api.Internal" } }
                });
            });

            services.AddAuthentication(options =>
            {
                options.DefaultScheme          = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.Authority = openIdConnectConfig.Url;
                options.Audience  = "auth_api";

                options.TokenValidationParameters.ValidateAudience = true;
                options.TokenValidationParameters.ValidateIssuer   = true;
                options.TokenValidationParameters.ValidateLifetime = true;
            })
            // Required for app authentication against the Auth service (for background services)
            .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
            {
                options.Authority    = openIdConnectConfig.Url;
                options.ClientSecret = openIdConnectConfig.ClientSecret;
                options.ClientId     = openIdConnectConfig.ClientId;

                options.Scope.Clear();
                options.Scope.Add("auth_api.Internal");
            });

            services.AddSingleton <IAuthorizationPolicyProvider, AuthorizationPolicyProvider>();

            services.RegisterAuthorizationHttpClientComponents <AuthServiceClientLocalization>(new AuthServiceCommunicationConfiguration
            {
                TokenName      = null, // not required
                ApiAccessToken = null, // not required
                AuthenticationServiceAddress = openIdConnectConfig.Url,
            }, new OpenIdConnectConfig
            {
                Url    = openIdConnectConfig.Url,
                Scopes = new List <string> {
                    openIdConnectConfig.AuthServiceScopeName
                },
                ClientId     = null, // not required
                ClientSecret = null, // not required
            }, new AuthServiceControllerBasePathsConfiguration
            {
                PermissionBasePath            = "api/v1/permission/",
                RoleBasePath                  = "api/v1/role/",
                UserBasePath                  = "api/v1/user/",
                RegistrationBasePath          = "api/v1/registration/",
                ExternalLoginProviderBasePath = "api/v1/externalLoginProvider/",
                FileResourceBasePath          = "api/v1/fileResource/",
                NonceBasePath                 = "api/v1/nonce/",
                ContactBasePath               = "api/v1/contact/",
                LoginCheckBasePath            = "Account/CheckLogin",
            });

            services.RegisterFulltextServiceClientComponents(new FulltextServiceClientConfiguration
            {
                Url = new Uri(endpointsConfiguration.Addresses["FulltextService"]),
                CreateCustomHandler = false
            });

            var credentials = credentialsConfiguration.FirstOrDefault(x => x.Type == "CardFiles");

            if (credentials == null)
            {
                throw new ArgumentException("Credentials for Card files not found");
            }

            services.RegisterCardFileClientComponents(new CardFilesCommunicationConfiguration
            {
                Url = new Uri(endpointsConfiguration.Addresses["CardFilesService"]),
                CreateCustomHandler = true,
                Username            = credentials.Username,
                Password            = credentials.Password
            });

            services.AddProjectImportServices();

            services.AddAutoMapper();

            // IoC
            var container = new DryIocContainerWrapper();

            container.RegisterLogger();
            Container = container;

            container.InnerContainer.AddNHibernateDefaultDatabase();
            container.InnerContainer.AddNHibernateForumDatabase();

            container.Install <MainServiceContainerRegistration>();
            container.Install <ForumCoreContainerRegistration>();

            return(container.CreateServiceProvider(services));
        }