Skip to content

Options

El patrón de opciones es una técnica común en aplicaciones .NET que permite centralizar la configuración en un solo lugar, facilitando la gestión y validación de las opciones de configuración. La clase SecurityOptions proporciona un conjunto de opciones para configurar la seguridad, específicamente la autenticación y autorización basadas en JWT. Estas opciones se configuran típicamente en el archivo appsettings.json de la aplicación.

SecurityOptions


La clase SecurityOptions proporciona un conjunto de opciones que pueden configurarse en el archivo appsettings.json de tu aplicación. Estas opciones son esenciales para definir el comportamiento y la configuración de seguridad, incluyendo la autenticación JWT.

namespace CodeDesignPlus.Net.Security.Abstractions.Options;
/// <summary>
/// Options to setting of the Security
/// </summary>
public class SecurityOptions
{
/// <summary>
/// Name of the sections used in the appsettings
/// </summary>
public static readonly string Section = "Security";
/// <summary>
/// Gets or sets the authority to use in the authentication
/// </summary>
public string Authority { get; set; }
/// <summary>
/// Gets or sets the client id to use in the authentication
/// </summary>
public string ClientId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to include error details in the authentication responses
/// </summary>
public bool IncludeErrorDetails { get; set; }
/// <summary>
/// Gets or sets a value indicating whether HTTPS metadata is required for the authentication
/// </summary>
public bool RequireHttpsMetadata { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the token audience must be validated
/// </summary>
public bool ValidateAudience { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the token issuer must be validated
/// </summary>
public bool ValidateIssuer { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the token lifetime must be validated
/// </summary>
public bool ValidateLifetime { get; set; }
/// <summary>
/// Gets or sets the valid issuer that will be used to check against the token's issuer
/// </summary>
[Required]
public string ValidIssuer { get; set; }
/// <summary>
/// Gets or sets the valid audiences that will be used to check against the token's audience
/// </summary>
[Required]
public IEnumerable<string> ValidAudiences { get; set; }
/// <summary>
/// Gets or sets the applications to use in the authentication
/// </summary>
public string[] Applications { get; set; } = [];
/// <summary>
/// Gets or sets the path of the certificate to use in the authentication
/// </summary>
public string CertificatePath { get; set; }
/// <summary>
/// Gets or sets the password of the certificate to use in the authentication
/// </summary>
public string CertificatePassword { get; set; }
/// <summary>
/// Get the certificate to use in the authentication
/// </summary>
/// <returns>The certificate to use in the authentication</returns>
/// <exception cref="FileNotFoundException">Thrown when the certificate file is not found at the specified path</exception>
public X509Certificate2 GetCertificate()
{
if (string.IsNullOrEmpty(this.CertificatePath))
return null;
var path = Path.Combine(AppContext.BaseDirectory, this.CertificatePath);
if (!File.Exists(path))
throw new FileNotFoundException($"The certificate file not found in the path: {path}");
return X509CertificateLoader.LoadPkcs12FromFile(path, this.CertificatePassword);
}
}

Propiedades

  • Section

    • Tipo: string
    • Descripción: Nombre de la sección en el archivo appsettings.json donde se encuentran las opciones de seguridad.
    • Valor Predeterminado: "Security"
    • Uso: Se utiliza para acceder a la configuración de seguridad dentro del archivo de configuración.
  • Authority

    • Tipo: string
    • Descripción: La autoridad (issuer) que se utiliza para la autenticación. Por ejemplo, la URL de un servidor de identidad.
    • Valor Predeterminado: null
    • Uso: Se utiliza para configurar la autenticación, especialmente cuando se usa un proveedor de identidad externo.
  • ClientId

    • Tipo: string
    • Descripción: El ID del cliente utilizado para la autenticación, si es necesario.
    • Valor Predeterminado: null
    • Uso: Identifica la aplicación cliente que está solicitando la autenticación.
  • IncludeErrorDetails

    • Tipo: bool
    • Descripción: Indica si se deben incluir detalles de errores en las respuestas de autenticación.
    • Valor Predeterminado: false
    • Uso: Útil para depuración y desarrollo, pero debe desactivarse en entornos de producción para evitar exponer información sensible.
  • RequireHttpsMetadata

    • Tipo: bool
    • Descripción: Indica si se requiere el uso de HTTPS para la comunicación de metadatos de autenticación.
    • Valor Predeterminado: true
    • Uso: Es una buena práctica de seguridad requerir HTTPS en la configuración de autenticación.
  • ValidateAudience

    • Tipo: bool
    • Descripción: Indica si se debe validar el público (audience) del token JWT.
    • Valor Predeterminado: true
    • Uso: Verifica que el token JWT esté destinado a esta aplicación específica.
  • ValidateIssuer

    • Tipo: bool
    • Descripción: Indica si se debe validar el emisor (issuer) del token JWT.
    • Valor Predeterminado: true
    • Uso: Verifica que el token JWT provenga de una fuente de confianza.
  • ValidateLifetime

    • Tipo: bool
    • Descripción: Indica si se debe validar la vida útil del token JWT.
    • Valor Predeterminado: true
    • Uso: Asegura que el token JWT no esté caducado.
  • ValidIssuer

    • Tipo: string
    • Descripción: El emisor (issuer) válido que se debe verificar contra el emisor del token.
    • Valor Predeterminado: null
    • Uso: Especifica el emisor aceptable para la autenticación.
    • Requerido: Debe configurarse si ValidateIssuer es true.
  • ValidAudiences

    • Tipo: IEnumerable<string>
    • Descripción: Los públicos (audiences) válidos que se deben verificar contra el público del token.
    • Valor Predeterminado: null
    • Uso: Especifica los públicos aceptables para la autenticación.
    • Requerido: Debe configurarse si ValidateAudience es true.
  • Applications

    • Tipo: string[]
    • Descripción: Arreglo de nombres de aplicaciones a las que se les permite usar la autenticación.
    • Valor Predeterminado: []
    • Uso: Se puede usar para configurar autenticación especifica por aplicación.
  • CertificatePath

    • Tipo: string
    • Descripción: La ruta del archivo del certificado X.509 utilizado para la firma de tokens.
    • Valor Predeterminado: null
    • Uso: Permite la firma de tokens con un certificado específico.
  • CertificatePassword

    • Tipo: string
    • Descripción: La contraseña del certificado X.509.
    • Valor Predeterminado: null
    • Uso: Proporciona la contraseña necesaria para acceder al certificado.

Métodos

La clase SecurityOptions proporciona métodos para cargar y validar el certificado X.509 utilizado para la firma de tokens.

GetCertificate

Este método carga el certificado X.509 desde la ruta especificada en CertificatePath, usando la contraseña en CertificatePassword.

public X509Certificate2 GetCertificate()
  • Tipo de retorno:
    • X509Certificate2: El certificado X.509 para usar en la validación del token. Retorna null si CertificatePath está vacío.
  • Excepciones:
    • FileNotFoundException: Si el archivo especificado en CertificatePath no se encuentra.
  • Ejemplo:
    var certificate = securityOptions.GetCertificate();
    if (certificate != null) {
    //Usar el certificado
    }

Validación

La clase SecurityOptions utiliza Data Annotations para validar las propiedades requeridas como ValidIssuer y ValidAudiences. Esto asegura que estas configuraciones estén presentes y sean válidas cuando se cargan.

Ejemplo de Configuración


A continuación se muestra un ejemplo de archivo appsettings.json que configura las opciones de seguridad:

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Security": {
"Authority": "https://codedesignplus.b2clogin.com/codedesignplus.onmicrosoft.com/B2C_1_signin/v2.0",
"IncludeErrorDetails": true,
"RequireHttpsMetadata": false,
"ValidateAudience": true,
"ValidateIssuer": true,
"ValidateLifetime": false,
"ValidIssuer": "https://codedesignplus.b2clogin.com/codedesignplus.onmicrosoft.com/B2C_1_signin/v2.0",
"ValidAudiences": [
"7f2aea10-b63c-44ce-8580-78ab3e5189aa"
]
}
}

Referencias Adicionales