Пример #1
0
        /// <summary>
        /// Carga el servicio de autenticación por token.
        /// </summary>
        /// <param name="services">Colección de servicios.</param>
        /// <param name="settings">Configuración del servicio de tokens.</param>
        /// <returns>IServiceCollection | ApplicationException: si JsonWebTokenSettings es nulo.</returns>
        internal static IServiceCollection LoadAuthJsonWebToken(
            this IServiceCollection services,
            JsonWebTokenSettings settings)
        {
            var config = settings.ToIsNullOrEmptyThrow(nameof(settings));

            if (config.Enabled.HasValue && config.Enabled.Value)
            {
                var validPrivateKey = config.PrivateKey.ToIsNullOrEmptyThrow(nameof(config.PrivateKey));

                var validPublicKey = config.PublicKey.ToIsNullOrEmptyThrow(nameof(config.PublicKey));

#if debug
                Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
#endif

                var rsa = RSA.Create();
                rsa.ImportRSAPublicKey(Convert.FromBase64String(validPublicKey), out _);
                var securityKey = new RsaSecurityKey(rsa)
                {
                    CryptoProviderFactory = new CryptoProviderFactory()
                    {
                        CacheSignatureProviders = false,
                    },
                };

                services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

                services
                .AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = config.AuthenticateScheme;

                    options.DefaultChallengeScheme = config.ChallengeScheme;
                })
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = config.RequireHttpsMetadata !.Value;

                    options.SaveToken = config.SaveToken !.Value;

                    options.IncludeErrorDetails = config.IncludeErrorDetails !.Value;

                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey         = securityKey,

                        ValidateIssuer = !string.IsNullOrWhiteSpace(config.Issuer),
                        ValidIssuer    = config.Issuer,

                        ValidateAudience = !string.IsNullOrWhiteSpace(config.Audience),
                        ValidAudience    = config.Audience,

                        ValidateLifetime  = config.ValidateLifetime !.Value,
                        LifetimeValidator = (notBefore, expires, securityToken, validationParameters) => expires > DateTime.UtcNow,

                        RequireExpirationTime = config.RequireExpirationTime !.Value,

                        // Establezca clockskew en cero para que los tokens caduquen exactamente a la hora de vencimiento del token (en lugar de 5 minutos más tarde)
                        ClockSkew = TimeSpan.Zero,
                    };

                    options.Events = new JwtBearerEvents
                    {
                        OnChallenge = context => throw new UnauthorizedAccessException(context.ToDetails()),
                    };
                });

                services.TryAddSingleton <IJsonWebTokenService>(new JsonWebTokenService(config));
            }

            return(services);
        }
Пример #2
0
        /// <summary>
        /// Indica si se utilizara el servicio de autenticación.
        /// </summary>
        /// <param name="settings">Configuración del servicio.</param>
        /// <returns>AuthenticationOptions | ApplicationException: si JsonWebTokenSettings es nulo.</returns>
        public AuthenticationOptions WithJsonWebToken(JsonWebTokenSettings settings)
        {
            AuthenticationSettings.JsonWebTokenSettings = settings.ToIsNullOrEmptyThrow(nameof(settings));

            return(this);
        }
Пример #3
0
 /// <summary>
 /// Inicializa una nueva instancia de la clase <see cref="JsonWebTokenService"/>.
 /// </summary>
 /// <param name="settings">Configuración para el token de sesión.</param>
 public JsonWebTokenService(JsonWebTokenSettings settings)
 => JsonWebTokenSettings = settings;