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

            if (!Request.Headers.TryGetValue(HomeAutomationLocalLightSystemId, out var homeAutomationLocalLightSystemId))
            {
                return(AuthenticateResult.NoResult());
            }

            var providedApiKey = apiKeyHeaderValues.FirstOrDefault();

            var clientId = homeAutomationLocalLightSystemId.FirstOrDefault();

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

            var existingApiKey = await _apiKeyService.Execute(providedApiKey);

            if (existingApiKey != null)
            {
                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, existingApiKey.Owner as string),
                    new Claim(ClaimTypes.PrimarySid, clientId as string)
                };

                claims.AddRange(existingApiKey.Roles.Select(role => new Claim(ClaimTypes.Role, role as string)));

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