Exemplo n.º 1
0
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.TryGetValue(API_KEY_HEADER_NAME, out var apiKeyHeaderValues))
            {
                return(AuthenticateResult.NoResult());
            }

            var providedApiKey = apiKeyHeaderValues.FirstOrDefault();

            if (apiKeyHeaderValues.Count == 0 || string.IsNullOrWhiteSpace(providedApiKey))
            {
                return(AuthenticateResult.NoResult());
            }

            string   creds       = Encoding.UTF8.GetString(Convert.FromBase64String(providedApiKey));
            ApiKey   apiKey      = JsonConvert.DeserializeObject <ApiKey>(creds);
            ApiKeyDB validApiKey = await _authService.IsValidApiKey(apiKey);

            if (validApiKey == null)
            {
                return(AuthenticateResult.Fail("Invalid api key"));
            }

            List <Claim> claims = new List <Claim>()
            {
                new Claim($"app.claims.{apiKey.ResourceId}", apiKey.Actions),
                new Claim(ClaimTypes.Name, validApiKey.Name),
                new Claim("Id", apiKey.Id.ToString())
            };
            ClaimsIdentity       identity  = new ClaimsIdentity(claims, Scheme.Name);
            ClaimsPrincipal      principal = new ClaimsPrincipal(identity);
            AuthenticationTicket ticket    = new AuthenticationTicket(principal, Scheme.Name);

            return(AuthenticateResult.Success(ticket));
        }
        public async Task <ApiKeyDB> IsValidApiKey(ApiKey apiKey)
        {
            if (DateTime.UtcNow > new DateTime(apiKey.ExpirationDate) || apiKey.Version != API_KEY_VERSION)
            {
                return(null);
            }
            ApiKeyDB keyDBInfo = await _repo.GetApiKeyInfoAsync(apiKey);

            PasswordVerificationResult res = _hasher.VerifyHashedPassword(null, keyDBInfo.Hash, apiKey.Secret);

            if (res == PasswordVerificationResult.Failed)
            {
                _logger.LogError($"Secret hash verification failed. Object: {JsonConvert.SerializeObject(keyDBInfo)}");
                return(null);
            }
            if (res == PasswordVerificationResult.SuccessRehashNeeded)
            {
                string hash = _hasher.HashPassword(null, apiKey.Secret);
                await _repo.UpdateApiKeyHashAsync(apiKey.Id, hash);
            }
            if (keyDBInfo.State == ApiKeyState.Inactive)
            {
                _logger.LogError($"Api key validation failed. Object: {JsonConvert.SerializeObject(keyDBInfo)}");
                return(null);
            }
            return(keyDBInfo);
        }