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 = _apiKeyService.IsValidApiKey(providedApiKey);

            if (existingApiKey != null)
            {
                var claims = new List <Claim>();

                claims.AddRange(existingApiKey.AssignedRoles.Select(role => new Claim(ClaimTypes.Role, role.ToString().ToLower())));

                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.NoResult());
        }