Exemplo 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 existingApiKey = await _apiKeyService.GetByKeyAsync(providedApiKey);

            if (existingApiKey == null)
            {
                return(AuthenticateResult.Fail("Invalid API Key provided."));
            }

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, existingApiKey.Owner)
            };

            claims.AddRange(existingApiKey.Permissions.Select(p => new Claim("https://westmoor.rpg/permissions", p)));

            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));
        }
 public async Task <ApiKeyEntity> GetByKeyAsync(string key) =>
 await _service.GetByKeyAsync(key);