All Downloads are FREE. Search and download functionalities are using the official Maven repository.

aspnetcore.2.1.Authentication.ApiAuthentication.mustache Maven / Gradle / Ivy

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace {{packageName}}.Authentication
{
    public class ApiKeyRequirement : IAuthorizationRequirement
    {
        public IReadOnlyList ApiKeys { get; set; }
        
        public string PolicyName { get; set; }

        public ApiKeyRequirement(IEnumerable apiKeys, string policyName)
        {
            ApiKeys = apiKeys?.ToList() ?? new List();
            PolicyName = policyName;
        }
    }

    public class ApiKeyRequirementHandler : AuthorizationHandler
    {

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ApiKeyRequirement requirement)
        {
            SucceedRequirementIfApiKeyPresentAndValid(context, requirement);
            return Task.CompletedTask;
        }

        private void SucceedRequirementIfApiKeyPresentAndValid(AuthorizationHandlerContext context, ApiKeyRequirement requirement)
        {
{{#authMethods}}{{#isApiKey}}
{{#-first}}
            if (context.Resource is AuthorizationFilterContext authorizationFilterContext)
            {
                var apiKey = "";
{{/-first}}
{{#isKeyInHeader}}
                apiKey = authorizationFilterContext.HttpContext.Request.Headers["{{keyParamName}}"].FirstOrDefault();
{{/isKeyInHeader}}
{{#isKeyInQuery}}
                apiKey = authorizationFilterContext.HttpContext.Request.Query["{{keyParamName}}"].FirstOrDefault();
{{/isKeyInQuery}}
{{#isKeyInCookie}}
                apiKey = authorizationFilterContext.HttpContext.Request.Cookies["{{keyParamName}}"] ?? null;
{{/isKeyInCookie}}
                if (requirement.PolicyName == "{{name}}" && apiKey != null && requirement.ApiKeys.Any(requiredApiKey => apiKey == requiredApiKey))
                {
                    context.Succeed(requirement);
                }
{{#-last}}
            }
{{/-last}}
{{/isApiKey}}{{/authMethods}}
        }
    }
}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy