using System.IdentityModel.Tokens.Jwt; using System.Text; using Elsa.Identity.Constants; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; namespace Elsa.Identity.Options; /// /// Represents options about token validation and generation. /// public class IdentityTokenOptions { /// /// The key to use when signing tokens /// public string SigningKey { get; set; } = null!; /// /// The issuer to use when creating and validating tokens /// public string Issuer { get; set; } = "http://elsa.api"; /// /// The audience to use when creating and validating tokens /// public string Audience { get; set; } = "http://elsa.api"; /// /// The lifetime of access tokens /// public TimeSpan AccessTokenLifetime { get; set; } = TimeSpan.FromHours(1); /// /// The lifetime of refresh tokens /// public TimeSpan RefreshTokenLifetime { get; set; } = TimeSpan.FromHours(2); /// /// Gets or sets the claim type that hold the tenant ID in the user's claims. /// If not set, will be used /// public string TenantIdClaimsType { get; set; } = CustomClaimTypes.TenantId; /// /// Creates a new from the . /// /// public SecurityKey CreateSecurityKey() => new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SigningKey)); /// /// Configures the with the values from this instance. /// /// The options to configure. public void ConfigureJwtBearerOptions(JwtBearerOptions options) { options.TokenValidationParameters = new TokenValidationParameters { IssuerSigningKey = CreateSecurityKey(), ValidAudience = Audience, ValidIssuer = Issuer, ValidateLifetime = true, LifetimeValidator = ValidateLifetime, NameClaimType = JwtRegisteredClaimNames.Name }; } private static bool ValidateLifetime(DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters) { return expires != null && expires > DateTime.UtcNow; } }