Exemplo n.º 1
0
        /// <summary>
        /// AddDataProtectionWithCertInRedis
        /// </summary>
        /// <param name="services"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        /// <exception cref="WebApiException"></exception>
        public static IServiceCollection AddDataProtectionWithCertInRedis(this IServiceCollection services, Action <DataProtectionSettings> action)
        {
            DataProtectionSettings dataProtectionSettings = new DataProtectionSettings();

            action(dataProtectionSettings);

            string redisKey = $"{dataProtectionSettings.ApplicationName}_{EnvironmentUtil.AspNetCoreEnvironment}_dpk";

            X509Certificate2 certificate2 = CertificateUtil.GetCertificateFromSubjectOrFile(
                dataProtectionSettings.CertificateSubject,
                dataProtectionSettings.CertificateFileName,
                dataProtectionSettings.CertificateFilePassword);

            ConfigurationOptions redisConfigurationOptions = ConfigurationOptions.Parse(dataProtectionSettings.RedisConnectString);

            redisConfigurationOptions.AllowAdmin = false;

            Policy
            .Handle <RedisConnectionException>()
            .WaitAndRetryForever(
                count => TimeSpan.FromSeconds(5 + count * 2),
                (exception, retryCount, timeSpan) =>
            {
                RedisConnectionException ex = (RedisConnectionException)exception;
                Log.Fatal(
                    exception,
                    $"DataProtection : Try {retryCount}th times. Wait For {timeSpan.TotalSeconds} seconds. Redis Can not connect {dataProtectionSettings.RedisConnectString} : {redisKey};"
                    );
            })
            .Execute(() =>
            {
                ConnectionMultiplexer redisMultiplexer = ConnectionMultiplexer.Connect(redisConfigurationOptions);

                services
                .AddDataProtection()
                .SetApplicationName(dataProtectionSettings.ApplicationName)
                .ProtectKeysWithCertificate(certificate2)
                .PersistKeysToStackExchangeRedis(redisMultiplexer, redisKey);
            });

            return(services);
        }
Exemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        /// <param name="audience">我是谁,即jwt是颁发给谁的</param>
        /// <param name="authority">当局。我该去向谁核实,即是谁颁发了这个jwt</param>
        /// <returns></returns>
        /// <exception cref="WebApiException"></exception>
        public static AuthenticationBuilder AddJwtAuthentication(this IServiceCollection services, IConfiguration configuration,
                                                                 Func <JwtBearerChallengeContext, Task> onChallenge,
                                                                 Func <TokenValidatedContext, Task> onTokenValidated,
                                                                 Func <AuthenticationFailedContext, Task> onAuthenticationFailed,
                                                                 Func <ForbiddenContext, Task> onForbidden,
                                                                 Func <MessageReceivedContext, Task> onMessageReceived)
        {
            JwtClientSettings jwtSettings = new JwtClientSettings();

            configuration.Bind(jwtSettings);

            X509Certificate2 encryptCert = CertificateUtil.GetCertificateFromSubjectOrFile(
                jwtSettings.JwtContentCertificateSubject,
                jwtSettings.JwtContentCertificateFileName,
                jwtSettings.JwtContentCertificateFilePassword);

            return
                (services
                 .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
                 .AddJwtBearer(jwtOptions =>
            {
//#if DEBUG
//                    jwtOptions.RequireHttpsMetadata = false;
//#endif
                jwtOptions.Audience = jwtSettings.Audience;
                jwtOptions.Authority = jwtSettings.Authority;
                jwtOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    RequireExpirationTime = true,
                    RequireSignedTokens = true,
                    RequireAudience = true,
                    TryAllIssuerSigningKeys = true,
                    ValidateAudience = true,
                    ValidateIssuer = true,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime = true,
                    TokenDecryptionKey = CredentialHelper.GetSecurityKey(encryptCert)
                };
                jwtOptions.Events = new JwtBearerEvents
                {
                    OnChallenge = onChallenge,
                    OnAuthenticationFailed = onAuthenticationFailed,
                    OnMessageReceived = onMessageReceived,
                    OnTokenValidated = onTokenValidated,
                    OnForbidden = onForbidden
                };
//#if DEBUG
//                    //这是为了ubuntu这货,在开发阶段不认开发证书。这个http请求,是由jwt audience 发向 jwt authority的。authority配置了正式证书后,就没问题了
//                    jwtOptions.BackchannelHttpHandler = new HttpClientHandler
//                    {
//                        ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
//                        {
//                            if (cert!.Issuer.Equals("CN=localhost", GlobalSettings.Comparison))
//                                return true;
//                            return errors == System.Net.Security.SslPolicyErrors.None;
//                        }
//                    };
//#endif
            }));
        }