using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace JwtClient
{
    class Program
    {
        static SecurityKey CreateSecurityKey()
        {
            return new InMemorySymmetricSecurityKey(Encoding.ASCII.GetBytes("hasloaliwjfaliwe4jlw34ijtaigjelitj34litj"));
        }

        static SigningCredentials CreateSigningCredentials()
        {
            return new SigningCredentials(
                CreateSecurityKey(),
                SecurityAlgorithms.HmacSha256Signature,
                SecurityAlgorithms.Sha256Digest);
        }

        static string CreateSecurityToken()
        {
            JwtSecurityToken securityToken = new JwtSecurityToken(
                issuer: "SecurityTokenProvider",
                lifetime: new System.IdentityModel.Protocols.WSTrust.Lifetime(DateTime.Now, DateTime.Now.AddDays(1)),
                audience: "localhost:57438",
                claims: new Claim[] { new Claim(ClaimTypes.Name, "pawel"), new Claim(ClaimTypes.Role, "admin") },
                signingCredentials: CreateSigningCredentials()
                );

            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            return tokenHandler.WriteToken(securityToken);
        }

        static async void GetResponseOperation()
        {
            try
            {
                var securityToken = CreateSecurityToken();
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", securityToken));
                HttpResponseMessage response = await client.GetAsync("http://localhost:57438/api/values");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
        }

        static void Main(string[] args)
        {
            Task task = new Task(GetResponseOperation);
            task.Start();
            task.Wait();
            Console.ReadLine();
        }
    }
}
