/// <summary> /// Performs authentication based on an API key. /// </summary> /// <param name="apiKeyId">The API key (the entity ID).</param> /// <returns>Returns a JWT on authentication success.</returns> public async Task <string> Authenticate(Guid apiKeyId) { // Get API key, throws if not found ApiKey apiKey = await ApiKeyService.GetApiKey(apiKeyId); // Reject authentication attempt if API key is disabled if (!apiKey.Enabled) { return(null); } // Set base claims List <Claim> claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, apiKey.Id.ToString()), new Claim(JwtRegisteredClaimNames.UniqueName, apiKey.Name), }; // Set fine-grained permission claims foreach (string permission in apiKey.Permissions) { claims.Add(new Claim(MisConstants.JWT_PERMISSIONS, permission)); } // Generate and return token return(GenerateNewToken(claims)); }
/// <summary> /// Sets up the service with all needed dependencies. /// </summary> /// <param name="loggerFactory">Factory to create loggers from.</param> /// <param name="passwordHashingService">Provides password hashing functionalities.</param> /// <param name="identityService">Provides identities.</param> /// <param name="domainService">Provides domain names.</param> /// <param name="configuration">App configuration for JWT signing information.</param> public AuthenticationService(ILoggerFactory loggerFactory, PasswordHashingService passwordHashingService, IdentityService identityService, DomainService domainService, ApiKeyService apiKeyService, IConfiguration configuration) { Logger = loggerFactory.CreateLogger <AuthenticationService>(); PasswordHashingService = passwordHashingService; IdentityService = identityService; DomainService = domainService; ApiKeyService = apiKeyService; // JWT-related configuration SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetValue <string>(ConfigurationPaths.JWT_SECRET))); SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); JwtLifetime = TimeSpan.FromMinutes(configuration.GetValue <int>(ConfigurationPaths.JWT_LIFETIME_IN_MINUTES)); JwtIssuer = configuration.GetValue <string>(ConfigurationPaths.JWT_ISSUER); }