using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Net.Http.Headers;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace JwtConsumer
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class WebApiApplication : System.Web.HttpApplication
    {
        static SecurityKey CreateSecurityKey()
        {
            return new InMemorySymmetricSecurityKey(Encoding.ASCII.GetBytes("hasloaliwjfaliwe4jlw34ijtaigjelitj34litj"));
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs args)
        {
            var rawAuthorizationHeader = this.Request.Headers["Authorization"];
            if (rawAuthorizationHeader != null)
            {
                var authenticationHeader = AuthenticationHeaderValue.Parse(rawAuthorizationHeader);
                if (authenticationHeader.Scheme.ToLower() == "bearer" && !string.IsNullOrEmpty(authenticationHeader.Parameter))
                {
                    var validationParameters = new TokenValidationParameters()
                    {
                        ValidIssuer = "SecurityTokenProvider",
                        ValidAudience = "localhost:57438",
                        IssuerSigningKey = CreateSecurityKey()
                    };

                    JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                    var claimPrincipal = tokenHandler.ValidateToken(authenticationHeader.Parameter, validationParameters);

                    Thread.CurrentPrincipal = HttpContext.Current.User = claimPrincipal;
                    return;
                }
            }

            Thread.CurrentPrincipal = HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(""), null);
        }
    }
}