Exemplo n.º 1
0
 private static SMTPClientSettings Parse(IConfigurationSection section, Func <string, string>?secureManager)
 {
     return(new SMTPClientSettings(
                section.GetValue <string>("Host"),
                section.GetValue("Port", 0),
                section.GetValue("UseSsl", false),
                section.GetValue <string?>("Sender"),
                CryptographyUtils.UnsealData(section.GetValue <string?>("UserName"), secureManager),
                CryptographyUtils.UnsealData(section.GetValue <string?>("Password"), secureManager)
                ));
 }
Exemplo n.º 2
0
        /// <summary>
        /// Constructor
        /// 构造函数
        /// </summary>
        /// <param name="httpClient">Http client, use IHttpClientFactory to create, services.AddHttpClient</param>
        /// <param name="smsUser">SMS User</param>
        /// <param name="smsKey">SMS key</param>
        /// <param name="secureManager">Secure manager</param>
        public SMSClient(HttpClient httpClient, IConfigurationSection section, Func <string, string>?secureManager = null) : this(
                httpClient,
                CryptographyUtils.UnsealData(section.GetValue <string>("SMSUser"), secureManager),
                CryptographyUtils.UnsealData(section.GetValue <string>("SMSKey"), secureManager),
                AddressRegion.GetById(section.GetValue <string>("Region")) ?? AddressRegion.CN
                )
        {
            // var templates = section.GetSection("Templates").Get<TemplateItem[]>();
            var templates = section.GetSection("Templates").GetChildren().Select(item => new TemplateItem(
                                                                                     Enum.Parse <TemplateKind>(item.GetValue <string>("Kind")),
                                                                                     item.GetValue <string>("TemplateId"),
                                                                                     item.GetValue <string>("EndPoint"),
                                                                                     item.GetValue <string>("Region"),
                                                                                     item.GetValue <string>("Language"),
                                                                                     item.GetValue <string>("Signature"),
                                                                                     item.GetValue("Default", false)
                                                                                     ));

            AddTemplates(templates);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Create connection factory
        /// 创建连接工厂
        /// </summary>
        /// <param name="section">Configuration section</param>
        /// <param name="secureManager">Secure manager</param>
        /// <returns>Connection factory</returns>
        public static ConnectionFactory CreateFactory(IConfigurationSection section, Func <string, string>?secureManager)
        {
            var factory = new ConnectionFactory
            {
                HostName                    = section.GetValue <string>("HostName"),
                UserName                    = CryptographyUtils.UnsealData(section.GetValue <string>("UserName"), secureManager),
                Password                    = CryptographyUtils.UnsealData(section.GetValue <string>("Password"), secureManager),
                ClientProvidedName          = section.GetValue <string>("ClientProvidedName"),
                AutomaticRecoveryEnabled    = section.GetValue("AutomaticRecoveryEnabled", true),
                DispatchConsumersAsync      = section.GetValue("DispatchConsumersAsync", false),
                UseBackgroundThreadsForIO   = section.GetValue("UseBackgroundThreadsForIO", false),
                ConsumerDispatchConcurrency = section.GetValue("ConsumerDispatchConcurrency", Environment.ProcessorCount - 1)
            };

            // VirtualHost
            var virtualHost = section.GetValue <string>("VirtualHost");

            if (!string.IsNullOrEmpty(virtualHost))
            {
                factory.VirtualHost = virtualHost;
            }

            // Port
            var port = section.GetValue <int?>("Port");

            if (port.HasValue)
            {
                factory.Port = port.Value;
            }

            // SSL
            var ssl = section.GetSection("Ssl");

            if (ssl.Exists())
            {
                factory.Ssl = ssl.Get <SslOption>();
            }

            return(factory);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Constructor
        /// 构造函数
        /// </summary>
        /// <param name="services">Dependency injection services</param>
        /// <param name="sslOnly">SSL only?</param>
        /// <param name="section">Configuration section</param>
        /// <param name="secureManager">Secure manager</param>
        /// <param name="issuerSigningKeyResolver">Issuer signing key resolver</param>
        /// <param name="tokenDecryptionKeyResolver">Token decryption key resolver</param>
        public JwtService(IServiceCollection services,
                          bool sslOnly,
                          IConfigurationSection section,
                          Func <string, string>?secureManager = null,
                          IssuerSigningKeyResolver?issuerSigningKeyResolver     = null,
                          TokenDecryptionKeyResolver?tokenDecryptionKeyResolver = null)
        {
            // Jwt section is required
            if (!section.Exists())
            {
                throw new ArgumentNullException(nameof(section), "No Section");
            }

            defaultIssuer   = section.GetValue <string>("DefaultIssuer") ?? DefaultIssuer;
            defaultAudience = section.GetValue <string>("DefaultAudience") ?? "All";

            validIssuer  = section.GetValue <string>("ValidIssuer");
            validIssuers = section.GetSection("ValidIssuers").Get <IEnumerable <string> >();
            if (string.IsNullOrEmpty(validIssuer))
            {
                validIssuer = defaultIssuer;
            }

            validAudience  = section.GetValue <string>("ValidAudience");
            validAudiences = section.GetSection("ValidAudiences").Get <IEnumerable <string> >();
            if (string.IsNullOrEmpty(validAudience) && validAudiences == null)
            {
                validAudience = defaultAudience;
            }

            // Whether validate audience
            var validateAudience = section.GetValue <bool?>("ValidateAudience");

            // Hash algorithms
            securityAlgorithms = section.GetValue("SecurityAlgorithms", SecurityAlgorithms.RsaSha512Signature);

            // Default 30 minutes
            AccessTokenMinutes = section.GetValue("AccessTokenMinutes", 30);

            // Default 90 days
            RefreshTokenDays = section.GetValue("RefreshTokenDays", 90);

            // https://stackoverflow.com/questions/53487247/encrypting-jwt-security-token-supported-algorithms
            // AES256, 256 / 8 = 32 bytes
            var encryptionKeyPlain = CryptographyUtils.UnsealData(section.GetValue <string>("EncryptionKey"), secureManager);

            // RSA crypto provider
            crypto = new RSACrypto(section, secureManager);

            // Default signing key resolver
            this.issuerSigningKeyResolver = (token, securityToken, kid, validationParameters) =>
            {
                if (issuerSigningKeyResolver == null)
                {
                    return(new List <RsaSecurityKey> {
                        new RsaSecurityKey(crypto.RSA)
                        {
                            KeyId = kid
                        }
                    });
                }

                var keys = issuerSigningKeyResolver(token, securityToken, kid, validationParameters);
                if (!keys.Any())
                {
                    keys = keys.Append(new RsaSecurityKey(crypto.RSA)
                    {
                        KeyId = kid
                    });
                }

                return(keys);
            };

            this.tokenDecryptionKeyResolver = (token, securityToken, kid, validationParameters) =>
            {
                if (tokenDecryptionKeyResolver == null)
                {
                    return(new List <SymmetricSecurityKey> {
                        new SymmetricSecurityKey(Encoding.UTF8.GetBytes(encryptionKeyPlain))
                        {
                            KeyId = kid
                        }
                    });
                }

                var keys = tokenDecryptionKeyResolver(token, securityToken, kid, validationParameters);
                if (!keys.Any())
                {
                    keys = keys.Append(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(encryptionKeyPlain))
                    {
                        KeyId = kid
                    });
                }

                return(keys);
            };

            // Adding Authentication
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                // Is SSL only
                options.RequireHttpsMetadata = sslOnly;

                // Useful forwarding the JWT in an outgoing request
                // https://stackoverflow.com/questions/57057749/what-is-the-purpose-of-jwtbeareroptions-savetoken-property-in-asp-net-core-2-0
                options.SaveToken = false;

                // Token validation parameters
                options.TokenValidationParameters = CreateValidationParameters();
                if (validateAudience != null)
                {
                    options.TokenValidationParameters.ValidateAudience = validateAudience.Value;
                }
            });
        }