Beispiel #1
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var apiKeyRepository = new ApiKeyRepository();

            var header = actionContext.Request.Headers.FirstOrDefault(x => x.Key == ApiConstants.AuthorizationHeaderName);

            if (header.Value == null || !header.Value.Any())
            {
                throw new HttpResponseException(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = $"Missing header {ApiConstants.AuthorizationHeaderName}"
                });
            }

            var maybeApiKey = apiKeyRepository.Get(header.Value.FirstOrDefault());

            if (!maybeApiKey.HasValue)
            {
                throw new HttpResponseException(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = $"No such API key exists"
                });
            }

            var apiKey = maybeApiKey.Value;

            if (!apiKey.Methods.Select(x => x.Method).Contains(Method) && !apiKey.Admin)
            {
                throw new HttpResponseException(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = $"API key {apiKey.Key} not allowed to execute method {Method}"
                });
            }
        }
Beispiel #2
0
        private bool ApiKeyIsValid(string apiKey)
        {
            bool isValid = false;

            try
            {
                var repo = new ApiKeyRepository();
                return(!string.IsNullOrEmpty(repo.Get(apiKey)));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return(isValid);
        }