Example #1
0
        private static void AddAuthentication(IServiceCollection services, IConfiguration configuration)
        {
            services.Configure <AuthenticationOptions>(configuration.GetSection("Authentication:AzureAd"));
            services.Configure <B2CAuthenticationOptions>(configuration.GetSection("Authentication:AzureAd:B2C"));
            services.Configure <B2CPolicies>(configuration.GetSection("Authentication:AzureAd:B2C:Policies"));

            var serviceProvider = services.BuildServiceProvider();

            var authOptions    = serviceProvider.GetService <IOptions <AuthenticationOptions> >();
            var b2cAuthOptions = serviceProvider.GetService <IOptions <B2CAuthenticationOptions> >();
            var b2cPolicies    = serviceProvider.GetService <IOptions <B2CPolicies> >();

            var distributedCache = serviceProvider.GetService <IDistributedCache>();

            services.AddSingleton(distributedCache);

            services.AddAuthentication(options =>
            {
                options.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = B2CAuthConstants.OpenIdConnectB2CAuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnectB2CAuthentication(b2cAuthOptions.Value, b2cPolicies.Value, distributedCache)
            .AddOpenIdConnectOrganizationalAuthentication(authOptions.Value, distributedCache);
        }
Example #2
0
        public void SetUp()
        {
            _msgContent = "";
            _guildId    = 1;
            _config     = ConfigService.BuildConfig();
            _mwsf       = ulong.Parse(_config.GetSection("SpecialGuilds").GetSection("MWSF").Value);
            _botSandBox = ulong.Parse(_config.GetSection("SpecialGuilds").GetSection("BotSandbox").Value);

            _mockMsg = new Mock <IUserMessage>();
            _mockMsg.Setup(x => x.Content).Returns(() => _msgContent);
            _msg = _mockMsg.Object as SocketMessage;

            var provider = new ServiceCollection().BuildServiceProvider();

            _mockSut = new Mock <CommandHandler>(provider)
            {
                CallBase = true
            };
            _mockSut.Setup(x => x.InitFields()).Verifiable();
            _mockSut.Setup(x => x.InitServices(It.IsAny <IServiceProvider>()));
            _mockSut.Setup(x => x.PrefixTriggers(It.IsAny <SocketUserMessage>(), It.IsAny <int>()));
            _mockSut.Setup(x => x.GetMessageGuildId(It.IsAny <SocketUserMessage>())).Returns(() => _guildId);

            _mockSut.Object.MWSF       = _mwsf;
            _mockSut.Object.BotSandbox = _botSandBox;
        }
Example #3
0
 public CryptionService(
     Microsoft.Extensions.Configuration.IConfiguration config,
     ILogger <CryptionService> logger)
 {
     Logger            = logger;
     symmetric         = Aes.Create();
     symmetric.Mode    = CipherMode.CBC;
     symmetric.Padding = PaddingMode.ISO10126;
     symmetric.KeySize = 256;
     symmetric.Key     = Convert.FromBase64String(config.GetSection("CRYPTION_KEY").Value);
     symmetric.IV      = Convert.FromBase64String(config.GetSection("CRYPTION_IV").Value);
     hashKey           = config.GetSection("CRYPTION_HASH").Value;
     createHash        = () =>
     {
         if (hash == null)
         {
             hash = new HMACSHA512(Convert.FromBase64String(hashKey));
         }
         return(hash);
     };
     symmetric2         = Aes.Create();
     symmetric2.Mode    = CipherMode.CBC;
     symmetric2.Padding = PaddingMode.ISO10126;
     symmetric2.KeySize = 256;
     symmetric2.Key     = Convert.FromBase64String(config.GetSection("CRYPTION_KEY2").Value);
     symmetric2.IV      = Convert.FromBase64String(config.GetSection("CRYPTION_IV2").Value);
 }
Example #4
0
        public ValidatorMoveService(Microsoft.Extensions.Configuration.IConfiguration configuration)
        {
            _configuration = configuration;

            RuleFor(x => x.MoveDetailDTO)
            .Custom((list, context) => {
                if (list.Select(s => s.Value).FirstOrDefault() > 500)
                {
                    context.AddFailure(_configuration
                                       .GetSection("DayOutOfRange").Value);
                }

                bool has = list.Where(o => o.Position > 1).Any(cus => cus.Value > 100);
                if (has)
                {
                    context.AddFailure(_configuration
                                       .GetSection("NumberOfElementsOrWeightOutOfRange").Value);
                }
            });


            RuleFor(z => z.IdentificationCard)
            .NotEmpty()
            .WithMessage(_configuration
                         .GetSection("DocumentCard").Value);

            RuleFor(z => z.IdentificationCard)
            .NotNull()
            .WithMessage(_configuration
                         .GetSection("DocumentCard").Value);;
        }
Example #5
0
        public MessagingProfile(Microsoft.Extensions.Configuration.IConfiguration config)
        {
            ConfigureEndpoint("Events")
            .AsOutbound()
            .AsEventDefault()
            .BindEvent <PaymentMethodCreated>()
            //see AuzureKeyVaultSample for a better way
            .UseAesEncryption(config.GetSection("SampleAESKey").Value)
            .UseAzureServiceBusTransport()
            ;
            ConfigureEndpoint("Events-Sub")
            .AsInbound()
            .BindEvent <PaymentMethodCreated>()
            //see AuzureKeyVaultSample for a better way
            .UseAesEncryption(config.GetSection("SampleAESKey").Value)
            .UseAzureServiceBusTransport()
            ;

            ConfigureEndpoint("Commands")
            .AsInboundOutbound()
            .UseAzureServiceBusTransport()
            ;

            ConfigureEndpoint("Replies")
            .AsInboundOutbound()
            .AsReplyDefault()
            .UseAzureServiceBusTransport()
            ;
        }
Example #6
0
        private static void ConfigureOptions(WebHostBuilderContext hostingContext, IServiceCollection services)
        {
            Microsoft.Extensions.Configuration.IConfiguration configuration = hostingContext.Configuration;

            services.AddOptions()
            .Configure <MongoOptions>(configuration.GetSection("Mongo"))
            .Configure <JWTOptions>(configuration.GetSection("JWT"));
        }
Example #7
0
        public Cosmos(Microsoft.Extensions.Configuration.IConfiguration config)
        {
            this.EndpointUri = config.GetSection("COSMOS_ENDPOINT_URI").Value;
            this.PrimaryKey  = config.GetSection("COSMOS_PRIMARY_KEY").Value;

            // Create a new instance of the Cosmos Client
            this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
        }
Example #8
0
 public CryptionService(
     Microsoft.Extensions.Configuration.IConfiguration config,
     ILogger <CryptionService> logger)
 {
     this.Logger       = logger;
     symmetric         = Aes.Create();
     symmetric.Mode    = CipherMode.CBC;
     symmetric.Padding = PaddingMode.ISO10126;
     symmetric.KeySize = 256;
     symmetric.Key     = Convert.FromBase64String(config.GetSection("CRYPTION_KEY").Value);
     symmetric.IV      = Convert.FromBase64String(config.GetSection("CRYPTION_IV").Value);
 }
Example #9
0
        /// <summary>
        ///
        /// </summary>
        public WeatherService(IHttpClient httpClient, IConfiguration configuration)
        {
            _httpClient = httpClient == null ?
                          throw new ArgumentNullException(nameof(httpClient)) : httpClient;

            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            _host    = configuration.GetSection("ClimaTempo:host").Value;
            _token   = configuration.GetSection("ClimaTempo:token").Value;
            _hostPut = configuration.GetSection("ClimaTempo:hostPut").Value;
        }
        public IActionResult Login(UserDto loginDto)
        {
            var userFromRepo = _authService.Login(loginDto.UserName, loginDto.PasswordHash);

            if (userFromRepo == null)
            {
                return(Unauthorized());
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.UserName)
            };

            var key             = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));
            var creds           = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new
            {
                token = tokenHandler.WriteToken(token), username = userFromRepo.UserName,
                fullname = userFromRepo.FirstName + " " + userFromRepo.LastName
            }));
        }
        public static void ConfigureAuthentication(this IServiceCollection services, IConfiguration configuration)
        {
            // configure database settings
            services.Configure <JwtSettings>(configuration.GetSection(nameof(JwtSettings)));
            services.AddSingleton(x => x.GetService <IOptions <JwtSettings> >().Value);

            // auth
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultSignInScheme       = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = true;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration.GetSection(nameof(JwtSettings))["JwtSecret"])),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });
        }
Example #12
0
        /// <summary>
        /// Registers Aspose Email License. Configure section 'Aspose-EmailLicense' in appsettings.json
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        public static void AddAsposeMailLicense(this IServiceCollection services, Microsoft.Extensions.Configuration.IConfiguration configuration)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            var license = new Aspose.Email.License();

            try
            {
                // Initializes a license from a stream
                var licenseInfo = configuration.GetSection("Aspose-EmailLicense").Value;
                if (String.IsNullOrWhiteSpace(licenseInfo))
                {
                    return;
                }
                var info = Encoding.UTF8.GetBytes(licenseInfo);
                using (var stream = new MemoryStream(info))
                {
                    license.SetLicense(stream);
                    Console.WriteLine("Aspose Email License set successfully.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"There was an error setting the Aspose Email License. Exception Message: {e.Message}");
                throw;
            }
        }
Example #13
0
        private async Task <string> GenerateJWtToken(User user)
        {
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.UserName)
            };
            var roles = await _userManager.GetRolesAsync(user);



            foreach (var role in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }
            var key = new SymmetricSecurityKey(Encoding.ASCII
                                               .GetBytes(_config.GetSection("AppSettings:Token").Value));
            var creds           = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };
            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Example #14
0
        private string GenerateToken(User user)
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, value: user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Username)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
        //public ApplicationSettingsService() : base()
        //{
        //}

        public ApplicationSettingsService(Microsoft.Extensions.Configuration.IConfiguration configuration) : base()
        {
            Configuration = configuration;

            BaseUrl =
                Configuration.GetSection("BaseUrl").Value;
        }
Example #16
0
 public AppModuleStarter(IConfiguration configuration)
 {
     foreach (var child in configuration.GetSection("DisabledModules:App").GetChildren())
     {
         _ignoredAppModules.Add(child.Value);
     }
 }
Example #17
0
        public async Task <ActionResult> Login([FromBody] UserForLoginDto userForLoginDto)
        {
            var user = await _authRepository.Login(userForLoginDto.UserName, userForLoginDto.Password);

            if (user == null)
            {
                return(Unauthorized());
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_configuration.GetSection("AppSettings:Token").Value);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.UserName)
                }),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key)
                                                            , SecurityAlgorithms.HmacSha512Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return(Ok(tokenString));
        }
Example #18
0
 public OSSongRepo(Data.SongDbContext context, IMemoryCache memoryCache, Microsoft.Extensions.Configuration.IConfiguration configuration)
 {
     _context     = context;
     _memoryCache = memoryCache;
     _useCache    = true;
     bool.TryParse(configuration.GetSection("AppBehavior")?["CacheSongs"], out _useCache);
 }
        public static void AddSecurityServices(this IServiceCollection services,
                                               Microsoft.Extensions.Configuration.IConfiguration configuration)
        {
            services.Configure <JSONWebTokensSettings>
                (configuration.GetSection("JSONWebTokensSettings"));


            services.AddSingleton <IUserManager <MyUser>, UserManager>();
            services.AddSingleton <ISignInManager <MyUser>, SignInManager>();
            services.AddTransient <IAuthenticationService, AuthenticationService>();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                o.RequireHttpsMetadata      = false;
                o.SaveToken                 = false;
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ClockSkew        = TimeSpan.Zero,
                    ValidIssuer      = configuration["JSONWebTokensSettings:Issuer"],
                    ValidAudience    = configuration["JSONWebTokensSettings:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JSONWebTokensSettings:Key"]))
                };

                o.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = c =>
                    {
                        c.NoResult();
                        c.Response.StatusCode  = 500;
                        c.Response.ContentType = "text/plain";
                        return(c.Response.WriteAsync(c.Exception.ToString()));
                    },
                    OnChallenge = context =>
                    {
                        context.HandleResponse();
                        context.Response.StatusCode  = 401;
                        context.Response.ContentType = "application/json";
                        var result = JsonConvert.SerializeObject("401 Not authorized");
                        return(context.Response.WriteAsync(result));
                    },
                    OnForbidden = context =>
                    {
                        context.Response.StatusCode  = 403;
                        context.Response.ContentType = "application/json";
                        var result = JsonConvert.SerializeObject("403 Not authorized");
                        return(context.Response.WriteAsync(result));
                    },
                };
            });
        }
 public static void Initialize(Microsoft.Extensions.Configuration.IConfiguration configuration)
 {
     if (configuration == null)
     {
         throw new ArgumentNullException(nameof(configuration));
     }
     Constants.EmailSender = configuration.GetSection("MailSettings").GetSection("Sender").Value;
 }
Example #21
0
        public static void ConfigureJWT(this IServiceCollection services, Microsoft.Extensions.Configuration.IConfiguration configuration)
        {
            var authSettings = configuration.GetSection(nameof(AuthSettings));

            services.Configure <AuthSettings>(authSettings);

            var signingKey           = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(authSettings[nameof(AuthSettings.SecretKey)]));
            var jwtAppSettingOptions = configuration.GetSection(nameof(JwtIssuerOptions));

            // Configure JwtIssuerOptions
            services.Configure <JwtIssuerOptions>(options =>
            {
                options.Issuer             = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                options.Audience           = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
                options.Minutes            = Convert.ToInt32(jwtAppSettingOptions[nameof(JwtIssuerOptions.Minutes)]);
            });
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(bearerOptions =>
            {
                bearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],
                    ValidAudience    = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],
                    IssuerSigningKey = signingKey
                };
            });
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            });

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("ApiAccess", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireClaim(ClaimTypes.Role, Constants.JWTAllowedRoles)
                               .RequireAuthenticatedUser().Build());
            });
        }
 public NotificationService(
     Microsoft.Extensions.Configuration.IConfiguration config,
     ICosmos cosmos,
     ILogger <NotificationService> logger)
 {
     this.Cosmos = cosmos;
     this.Logger = logger;
     this.LastNotificationCheckInterval = Convert.ToInt32(config.GetSection("LAST_NOTIFICATION_CHECK_INTERVAL").Value);
 }
Example #23
0
        public static void Configure(IConfiguration configuration)
        {
            var timeBetweenCalls = configuration.GetSection("Http")?["TimeBetweenCallsInSeconds"];

            if (float.TryParse(timeBetweenCalls, out var timeBetweenCallsInSeconds))
            {
                _timeBetweenCallsInSeconds = TimeSpan.FromSeconds(timeBetweenCallsInSeconds);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="schemaSection"></param>
        /// <returns></returns>
        public static WeChatConfig GetOptionsFromConfig([NotNull] Microsoft.Extensions.Configuration.IConfiguration configuration, [NotNull] string schemaSection)
        {
            schemaSection = schemaSection ?? throw new ArgumentNullException(nameof(schemaSection));

            var section    = configuration.GetSection(schemaSection);
            var configJson = section.ToJObject().ToString();
            var config     = JsonConvert.DeserializeObject <WeChatConfig>(configJson);

            config.SchemaSection = schemaSection;
            return(config);
        }
        /// <summary>
        /// Loads NLog LoggingConfiguration from appsettings.json from NLog-section
        /// </summary>
        public static ISetupBuilder LoadNLogConfigFromSection(this ISetupBuilder setupBuilder, Microsoft.Extensions.Configuration.IConfiguration configuration)
        {
            setupBuilder.SetupExtensions(s => s.RegisterConfigSettings(configuration));
            var nlogConfig = configuration.GetSection("NLog");

            if (nlogConfig != null && nlogConfig.GetChildren().Any())
            {
                setupBuilder.LogFactory.Configuration = new NLogLoggingConfiguration(nlogConfig, setupBuilder.LogFactory);
            }
            return(setupBuilder);
        }
Example #26
0
        public BotManager(Microsoft.Extensions.Configuration.IConfiguration configuration)
        {
                        #pragma warning disable IDE0028 // Simplify collection initialization
            factories = new Dictionary <BotEngine, IBotFactory>();
            factories.Add(BotEngine.Mocking, new MockingBotFactory());
            factories.Add(BotEngine.Telegram, new TelegramBotFactory(configuration.GetSection("Telegram")));

            bots = new Dictionary <BotEngine, ConcurrentDictionary <String, BotWrapper> >();
            bots.Add(BotEngine.Mocking, new ConcurrentDictionary <String, BotWrapper>(StringComparer.InvariantCultureIgnoreCase));
            bots.Add(BotEngine.Telegram, new ConcurrentDictionary <String, BotWrapper>(StringComparer.InvariantCultureIgnoreCase));
                        #pragma warning restore IDE0028 // Simplify collection initialization
        }
Example #27
0
        public IBot CreateBot(String key)
        {
            var cs = confs.GetSection(key);

            var cfg = new BotCore.Types.Base.Configure
            {
                Token   = cs["Token"],
                WebHook = cs["WebHookUri"]
            };

            return(new BotCore.Telegram.TelegramBot(cfg));
        }
        public async Task <ActionResult> Login([FromBody] LoginCommand loginCommand)
        {
            UserVM user = await Mediator.Send(loginCommand);

            return(Ok(new
            {
                token = TokenManager.GenerateAccessToken(configuration.GetSection("AppSettings:Token").Value, new Infrastructure.Identity.User()
                {
                    UserName = user.Username, Roles = user.UserRoles
                })
            }));
        }
 public static IServiceCollection UseSocialServices(this IServiceCollection services,
                                                    IConfiguration configuration)
 {
     services.AddDbContext <SocialApiContext>();
     services.Configure <ImageRepoConfiguration>(configuration.GetSection("ImageRepo"));
     services.AddScoped <AuditRepository>();
     services.AddScoped <UserRepository>();
     services.AddScoped <PostRepository>();
     services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
     services.AddScoped <TenantAccessor>();
     return(services);
 }
        public void AddServices(IServiceCollection services, IConfiguration configuration)
        {
            services.AddDbContext <BookFastContext>(options => options.UseSqlServer(configuration["Data:DefaultConnection:ConnectionString"]));

            services.AddScoped <IFacilityDataSource, FacilityDataSource>();
            services.AddScoped <IAccommodationDataSource, AccommodationDataSource>();

            services.AddScoped <IFacilityMapper, FacilityMapper>();
            services.AddScoped <IAccommodationMapper, AccommodationMapper>();

            services.Configure <SearchQueueOptions>(configuration.GetSection("Data:Azure:Storage"));
            services.AddSingleton <ISearchIndexer, SearchIndexer>();
        }