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

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

There is a newer version: 7.9.0
Show newest version
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
{
    /// 
    /// A requirement that an ApiKey must be present.
    /// 
    public class ApiKeyRequirement : IAuthorizationRequirement
    {
        /// 
        /// Get the list of api keys
        /// 
        public IReadOnlyList ApiKeys { get; }

        /// 
        /// Get the policy name,
        /// 
        public string PolicyName { get; }

        /// 
        /// Create a new instance of the  class.
        /// 
        /// 
        /// 
        public ApiKeyRequirement(IEnumerable apiKeys, string policyName)
        {
            ApiKeys = apiKeys?.ToList() ?? new List();
            PolicyName = policyName;
        }
    }

    /// 
    /// Enforce that an api key is present.
    /// 
    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}}
            if (context.Resource is AuthorizationFilterContext authorizationFilterContext)
            {
{{#isKeyInHeader}}
                var apiKey = authorizationFilterContext.HttpContext.Request.Headers["{{keyParamName}}"].FirstOrDefault();
{{/isKeyInHeader}}
{{#isKeyInQuery}}
                var apiKey = authorizationFilterContext.HttpContext.Request.Query["{{keyParamName}}"].FirstOrDefault();
{{/isKeyInQuery}}
{{#isKeyInCookie}}
                var apiKey = authorizationFilterContext.HttpContext.Request.Cookies["{{keyParamName}}"] ?? null;
{{/isKeyInCookie}}
                if (requirement.PolicyName == "{{name}}" && apiKey != null && requirement.ApiKeys.Any(requiredApiKey => apiKey == requiredApiKey))
                {
                    context.Succeed(requirement);
                }
            }
{{/isApiKey}}{{/authMethods}}
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy