예제 #1
0
        public async Task <CommandResult> Handle(CreateApiKeyCommand command)
        {
            var result = new CommandResult();

            var readableKey = Guid.NewGuid().ToString("N");
            var apiKey      = new ApiKey
            {
                AppId     = command.AppId,
                Name      = command.Name,
                CreatedAt = DateTimeOffset.UtcNow,
                Key       = ApiKey.HashKey(readableKey, command.AppId)
            };

            if (!await _validator.IsValid(apiKey))
            {
                result.AddValidationErrors(_validator.Errors);
            }
            else
            {
                await _applicationStore.AddApiKey(apiKey);

                var resultData = new CreateApiKeyResultData
                {
                    ReadableKey = readableKey,
                    ApiKey      = apiKey
                };
                result.SetResultData(resultData);
            }
            return(result);
        }
예제 #2
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."));
        }