LSTANCZYK
10/5/2016 - 9:59 PM

Custom OWIN Middleware Sample

Custom OWIN Middleware Sample

 #region API KEY Authentication
    public static class APIKeyDefaults
    {
        public const string AuthenticationType = "Apikey";
    }

    public class APIKeyAuthenticationOptions : AuthenticationOptions
    {
        /// <summary>
        /// Creates an instance of API Key authentication options with default values.
        /// </summary>
        public APIKeyAuthenticationOptions()
            : base(APIKeyDefaults.AuthenticationType)
        {
        }
    }

    public class APIKeyAuthenticationHandler : AuthenticationHandler<APIKeyAuthenticationOptions>
    {
        private readonly ILogger logger;

        public APIKeyAuthenticationHandler(ILogger logger)
        {
            this.logger = logger;
        }

        protected override async Task<Microsoft.Owin.Security.AuthenticationTicket> AuthenticateCoreAsync()
        {
            var properties = new AuthenticationProperties();
            // Find apiKey in default location
            string apiKey = null;
            string authorization = Request.Headers.Get("Authorization");
            if (!string.IsNullOrEmpty(authorization))
            {
                if (authorization.StartsWith("Apikey ", StringComparison.OrdinalIgnoreCase))
                {
                    apiKey = authorization.Substring("Apikey ".Length).Trim();
                }
                else
                {
                    this.logger.WriteInformation("Authorization skipped.");

                    return new AuthenticationTicket(null, properties);
                }
            }
            else
            {
                this.logger.WriteWarning("Authorization header not found");

                return new AuthenticationTicket(null, properties);
            }

            var userClaim = new Claim(ClaimTypes.Name, "gvdasa");
            var allClaims = Enumerable.Concat(new Claim[] { userClaim }, Enumerable.Empty<Claim>());

            var identity = new ClaimsIdentity(allClaims, APIKeyDefaults.AuthenticationType);
            var principal = new ClaimsPrincipal(new ClaimsIdentity[] { identity });

            // resulting identity values go back to caller
            return new AuthenticationTicket(identity, properties);
        }

    }

    public class APIKeyAuthenticationMiddleware : AuthenticationMiddleware<APIKeyAuthenticationOptions>
    {
        private readonly ILogger logger;

        public APIKeyAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, APIKeyAuthenticationOptions options)
            : base(next, options)
        {
            this.logger = app.CreateLogger<AuthenticationHandler>();
        }

        protected override AuthenticationHandler<APIKeyAuthenticationOptions> CreateHandler()
        {
            return new APIKeyAuthenticationHandler(logger);
        }
    }

    public static class APIKeyAuthenticationExtensions
    {
        public static IAppBuilder UseAPIKeyAuthentication(this IAppBuilder app, APIKeyAuthenticationOptions options = null)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }

            app.Use(typeof(APIKeyAuthenticationMiddleware), app, options != null ? options : new APIKeyAuthenticationOptions());
            app.UseStageMarker(PipelineStage.Authenticate);
            return app;
        }
    }
    #endregion