예제 #1
0
        public static bool TokenStatus(string token)
        {
            Chilkat.Jwt jwt = new Chilkat.Jwt();
            //Chilkat.Jwt jwt = new Chilkat.Jwt();
            //string payload = jwt.GetPayload(token);
            //Console.WriteLine(payload);


            Chilkat.PublicKey pubKey = new Chilkat.PublicKey();
            bool success             = pubKey.LoadFromFile("C:\\Users\\Lenovo\\Desktop\\Detyra1_DS-Gr-6-master\\ds\\bin\\Debug\\netcoreapp3.0\\keys\\" +
                                                           GetTuser(token, false) + ".pub.pem");

            Console.WriteLine(GetTuser(token, false));
            bool sigVerified = jwt.VerifyJwtPk(token, pubKey);

            if (sigVerified)
            {
                // Console.WriteLine("valid " + Convert.ToString(sigVerified));
                int  leeway     = 60;
                bool bTimeValid = jwt.IsTimeValid(token, leeway);
                Console.WriteLine("time constraints valid: " + Convert.ToString(bTimeValid));
                if (bTimeValid)
                {
                    // Console.WriteLine(GetTuser(token, true));
                }
                return(true);
            }
            else
            {
                // Console.WriteLine("nuk eshte valid");
                return(false);
            }
        }
예제 #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(x => x
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials()
                        );


            app.Use(async(context, next) =>
            {
                Console.WriteLine(context.Request.Path.Value);
                if (context.Request.Path.Value == "/" || context.Request.Path.Value.Contains("/assets") || context.Request.Path.Value.StartsWith("/auth") || context.Request.Path.Value.Contains("/signIn") || context.Request.Path.Value.Contains("/signUp") || context.Request.Path.Value.Contains("/socialSignIn"))
                {
                    await next();
                }
                else
                {
                    Microsoft.AspNetCore.Http.IRequestCookieCollection cookies = context.Request.Cookies;
                    var token = cookies["TOKEN"];
                    Console.WriteLine(token);
                    // var token = context.Request.Cookies["TOKEN"] ;
                    // var token = context.Request.Headers["Authorization"];
                    Chilkat.Global glob = new Chilkat.Global();
                    glob.UnlockBundle("Anything for 30-day trial");

                    using (var client = new ConsulClient())
                    {
                        string ConsulIpHost   = "http://consul:8500";
                        client.Config.Address = new Uri(ConsulIpHost);
                        // client.Config.Address = new Uri("http://172.23.238.173:8500");
                        var getpair2  = client.KV.Get("myPublicKey");
                        string secret = System.Text.Encoding.UTF8.GetString(getpair2.Result.Response.Value);
                        Chilkat.Rsa rsaExportedPublicKey = new Chilkat.Rsa();
                        rsaExportedPublicKey.ImportPublicKey(secret);
                        var publickey = rsaExportedPublicKey.ExportPublicKeyObj();
                        Console.WriteLine(rsaExportedPublicKey.ExportPublicKey());
                        var jwt = new Chilkat.Jwt();
                        if (jwt.VerifyJwtPk(token, publickey) && jwt.IsTimeValid(token, 0))
                        {
                            await next();
                        }
                        else
                        {
                            context.Response.StatusCode = 403;
                            await context.Response.WriteAsync("UnAuthorized");
                        }
                    }
                }
            });
            app.UseWebSockets();
            app.UseOcelot().Wait();
        }
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            Chilkat.Global glob = new Chilkat.Global();
            glob.UnlockBundle("Anything for 30-day trial");

            Chilkat.Rsa rsaKey = new Chilkat.Rsa();

            rsaKey.GenerateKey(1024);
            var rsaPrivKey = rsaKey.ExportPrivateKeyObj();

            var rsaPublicKey         = rsaKey.ExportPublicKeyObj();
            var rsaPublicKeyAsString = rsaKey.ExportPublicKey();

            Chilkat.JsonObject jwtHeader = new Chilkat.JsonObject();
            jwtHeader.AppendString("alg", "RS256");
            jwtHeader.AppendString("typ", "JWT");

            Chilkat.JsonObject claims = new Chilkat.JsonObject();
            claims.AppendString("Email", "*****@*****.**");
            claims.AppendString("Test", "test1");

            Chilkat.Jwt jwt = new Chilkat.Jwt();

            string token = jwt.CreateJwtPk(jwtHeader.Emit(), claims.Emit(), rsaPrivKey);

            Console.WriteLine("This is the token generated");
            Console.WriteLine(token);

            // Verifying Token using Public Key
            Console.WriteLine(jwt.VerifyJwtPk(token, rsaPublicKey));
            Console.WriteLine(jwt.GetPayload(token));

            // Importing public key
            Chilkat.Rsa rsaExportedPublicKey = new Chilkat.Rsa();
            Console.WriteLine(rsaExportedPublicKey.ImportPublicKey(rsaPublicKeyAsString));
            Console.WriteLine(jwt.VerifyJwtPk(token, rsaExportedPublicKey.ExportPublicKeyObj()));

            // Store the value in Consul KV
            using (var client = new ConsulClient())
            {
                var putPair = new KVPair("secretkey")
                {
                    Value = Encoding.UTF8.GetBytes(rsaPublicKeyAsString)
                };

                var putAttempt = await client.KV.Put(putPair);

                if (putAttempt.Response)
                {
                    var getPair = await client.KV.Get("secretkey");

                    if (getPair.Response != null)
                    {
                        Console.WriteLine("Getting Back the Stored String");
                        Console.WriteLine(Encoding.UTF8.GetString(getPair.Response.Value, 0, getPair.Response.Value.Length));
                    }
                }
            }
        }
예제 #4
0
        // This method is resposible of generating JWT token
        public async static Task <string> GenerateTokenAsync(string Email)
        {
            Chilkat.Global glob = new Chilkat.Global();
            glob.UnlockBundle("Anything for 30-day trial");

            string token = "";

            //Creating JWT header using chilkat
            Chilkat.JsonObject jwtHeader = new Chilkat.JsonObject();
            jwtHeader.AppendString("alg", "RS256");
            jwtHeader.AppendString("typ", "JWT");

            //Adding Token claims
            Chilkat.JsonObject claims = new Chilkat.JsonObject();
            claims.AppendString("Email", Email);

            //Adding Token Expiration time
            Chilkat.Jwt jwt         = new Chilkat.Jwt();
            int         curDateTime = jwt.GenNumericDate(0);

            claims.AddIntAt(-1, "exp", curDateTime + 720);

            //Ading consul for putting and getting public and private key
            using (var client = new ConsulClient())
            {
                client.Config.Address = new Uri("http://172.23.238.173:8500");

                var getPair = client.KV.Get("myPrivateKey");


                if (getPair.Result.Response != null)
                {
                    string      secret = System.Text.Encoding.UTF8.GetString(getPair.Result.Response.Value);
                    Chilkat.Rsa rsaExportedPrivateKey = new Chilkat.Rsa();
                    rsaExportedPrivateKey.ImportPrivateKey(secret);
                    var rsaPrivKey = rsaExportedPrivateKey.ExportPrivateKeyObj();

                    token = jwt.CreateJwtPk(jwtHeader.Emit(), claims.Emit(), rsaPrivKey);
                }
                else
                {
                    await TokenManager.KeyGeneratorAsync(client);

                    var getPair1 = client.KV.Get("myPrivateKey");

                    string secret = System.Text.Encoding.UTF8.GetString(getPair1.Result.Response.Value);

                    Chilkat.Rsa rsaExportedPrivateKey = new Chilkat.Rsa();
                    rsaExportedPrivateKey.ImportPrivateKey(secret);

                    token = jwt.CreateJwtPk(jwtHeader.Emit(), claims.Emit(), rsaExportedPrivateKey.ExportPrivateKeyObj());
                }
            }

            //jwt.AutoCompact = true;
            //return JsonConvert.SerializeObject(token);
            return(token);
        }
예제 #5
0
        public static string GenjeroTokenin(string user)
        {
            Chilkat.PrivateKey privKey = new Chilkat.PrivateKey();
            bool success = privKey.LoadEncryptedPemFile("C:\\Users\\Lenovo\\Desktop\\Detyra1_DS-Gr-6-master\\ds\\bin\\Debug\\netcoreapp3.0\\keys\\" + user + ".pem", "passwd");

            if (!success)
            {
                return("Nuk ekziston Celsi ose nuk mund te hapet");
            }
            Chilkat.Jwt        jwt  = new Chilkat.Jwt();
            Chilkat.JsonObject jose = new Chilkat.JsonObject();
            //  Use RS256.  Pass the string "RS384" or "RS512" to use RSA with SHA-384 or SHA-512.
            success = jose.AppendString("alg", "RS256");
            success = jose.AppendString("typ", "JWT");
            //  Now build the JWT claims (also known as the payload)
            Chilkat.JsonObject claims = new Chilkat.JsonObject();

            success = claims.AppendString("sub", user);
            DateTime aDay           = DateTime.Now;
            TimeSpan a20min         = new System.TimeSpan(0, 0, 20, 0);
            DateTime after20minutes = aDay.Add(a20min);

            string k = after20minutes.ToString();

            success = claims.AppendString("Valid-till", k);
            //success = claims.AppendString("aud", "http://example.com");
            //  Set the timestamp of when the JWT was created to now.
            int curDateTime = jwt.GenNumericDate(0);

            success = claims.AddIntAt(-1, "iat", curDateTime);

            //  Set the "not process before" timestamp to now.
            success = claims.AddIntAt(-1, "nbf", curDateTime);

            //  Set the timestamp defining an expiration time (end time) for the token
            //  to be now + 20 minutes (1200 seconds)
            success = claims.AddIntAt(-1, "exp", curDateTime + 1200);
            // adding the tme when its not valid


            //  Produce the smallest possible JWT:
            jwt.AutoCompact = true;


            //  Create the JWT token.  This is where the RSA signature is created.
            string token = jwt.CreateJwtPk(jose.Emit(), claims.Emit(), privKey);

            //Console.WriteLine(token);
            return(token);
        }
예제 #6
0
        public static string GetTuser(string token, bool op)
        {
            Chilkat.Jwt jwt     = new Chilkat.Jwt();
            string      payload = jwt.GetPayload(token);

            string[] Claims = payload.Split(",");

            string[] Tedhenat = Claims[0].Split(":");
            int      f        = Tedhenat[0].Length;

            string user = Tedhenat[1].Substring(1, f);
            string koha = Claims[1];

            if (op)
            {
                return(koha);
            }
            else
            {
                return(user);
            }
        }