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

            var providedApiKey = apiKeyHeaderValues.FirstOrDefault();

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

            var appId        = Context.GetRouteValue("appId").ToString();
            var hashedApiKey = ApiKeyClass.HashKey(providedApiKey, appId);
            var apiKey       = (await _applicationStore.GetApiKeys(new ApiKeysQuery {
                AppId = appId, Key = hashedApiKey
            })).FirstOrDefault();

            if (apiKey != null)
            {
                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, apiKey.Name)
                };

                var identity   = new ClaimsIdentity(claims, Options.AuthenticationType);
                var identities = new List <ClaimsIdentity> {
                    identity
                };
                var principal = new ClaimsPrincipal(identities);
                var ticket    = new AuthenticationTicket(principal, Options.Scheme);

                return(AuthenticateResult.Success(ticket));
            }

            return(AuthenticateResult.Fail("Invalid API Key provided."));
        }