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

handlebars.aspnetcore.Security.ApiKeyAuthenticationHandler.mustache Maven / Gradle / Ivy

There is a newer version: 1.0.54
Show newest version
using System;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace {{packageName}}.Security
{
    /// 
    /// class to handle api_key security.
    /// 
    public class ApiKeyAuthenticationHandler : AuthenticationHandler
    {
        /// 
        /// scheme name for authentication handler.
        /// 
        public const string SchemeName = "ApiKey";

        public ApiKeyAuthenticationHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
        {
        }

        /// 
        /// verify that require api key header exist and handle authorization.
        /// 
        protected override async Task HandleAuthenticateAsync()
        {
            if (!Request.Headers.ContainsKey("api_key"))
            {
                return AuthenticateResult.Fail("Missing Authorization Header");
            }

            // do magic here!

            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, "changeme"),
                new Claim(ClaimTypes.Name, "changeme"),
            };
            var identity = new ClaimsIdentity(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(identity);
            var ticket = new AuthenticationTicket(principal, Scheme.Name);

            return AuthenticateResult.Success(ticket);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy