Example #1
0
 public static bool Check(IOwinContext ctx)
 {
     if (ctx.Request.Headers["_Autorize"] != null)
     {
         string[] base_path = ctx.Request.PathBase.ToString().Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
         if (base_path.Length < 2)
         {
             return(false);
         }
         string jwt = ctx.Request.Headers["_Autorize"].ToString();
         if (String.IsNullOrEmpty(jwt))
         {
             return(false);
         }
         Dictionary <string, object> claims = Jwt.Decode(jwt);
         if (claims == null)
         {
             return(false);
         }
         if (Jwt.Check(claims, null, null))
         {
             return(true);
         }
     }
     return(true);
 }
Example #2
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                log.Info("C# HTTP trigger function processed a request.");

                var data = await RequestDecoder.Decode <SessionCreatePostModel>(req);

                try
                {
                    var jwt = Jwt.Decode(data.password);
                    if (jwt.subject != data.username)
                    {
                        throw new Exception("Username/JWT-subject mismatch");
                    }
                }
                catch
                {
                    throw new HttpResponseException(req.CreateErrorResponse(HttpStatusCode.Forbidden, "Forbidden"));
                }

                var response = new SessionResponseModel
                {
                    id       = Guid.NewGuid().ToString("N"),
                    username = data.username
                };
                return(req.CreateResponse(HttpStatusCode.OK, response));
            }
            catch (HttpResponseException error)
            {
                return(error.Response);
            }
        }
Example #3
0
 public static JObject UserFromCookie()
 {
     if (HttpContext.Current.Request.Cookies["_Autorize"] != null)
     {
         JObject user   = new JObject();
         string  cookie = HttpContext.Current.Request.Cookies["_Autorize"].Value;
         if (String.IsNullOrEmpty(cookie))
         {
             return(null);
         }
         Dictionary <string, object> claims = Jwt.Decode(cookie);
         object id;
         if (claims.TryGetValue("id", out id))
         {
             user["id"] = id.ToString();
         }
         object name;
         if (claims.TryGetValue("name", out name))
         {
             user["name"] = name.ToString();
         }
         object access_level;
         if (claims.TryGetValue("access_level", out access_level))
         {
             user["access_level"] = Convert.ToInt32(access_level);
         }
         return(user);
     }
     return(null);
 }
        public Task <IdentityTokenValidationResult> ValidateAsync(string identityToken, string clientId, ProviderInformation providerInformation)
        {
            var fail = new IdentityTokenValidationResult
            {
                Success = false
            };

            var e      = Base64Url.Decode(providerInformation.KeySet.Keys.First().E);
            var n      = Base64Url.Decode(providerInformation.KeySet.Keys.First().N);
            var pubKey = PublicKey.New(e, n);

            var json    = Jwt.Decode(identityToken, pubKey);
            var payload = JObject.Parse(json);

            var issuer   = payload["iss"].ToString();
            var audience = payload["aud"].ToString();

            if (issuer != providerInformation.IssuerName)
            {
                fail.Error = "Invalid issuer name";
                return(Task.FromResult(fail));
            }

            if (audience != clientId)
            {
                fail.Error = "Invalid audience";
                return(Task.FromResult(fail));
            }

            var exp = payload["exp"].ToString();
            var nbf = payload["nbf"].ToString();

            var utcNow    = DateTime.UtcNow;
            var notBefore = long.Parse(nbf).ToDateTimeFromEpoch();
            var expires   = long.Parse(exp).ToDateTimeFromEpoch();

            if (notBefore > utcNow.Add(ClockSkew))
            {
                fail.Error = "Token not valid yet";
                return(Task.FromResult(fail));
            }

            if (expires < utcNow.Add(ClockSkew.Negate()))
            {
                fail.Error = "Token expired";
                return(Task.FromResult(fail));
            }

            return(Task.FromResult(new IdentityTokenValidationResult
            {
                Success = true,
                Claims = payload.ToClaims(),
                SignatureAlgorithm = "RS256"
            }));
        }
        public void DecodeHS384()
        {
            //given
            string token = "eyJhbGciOiJIUzM4NCIsImN0eSI6InRleHRcL3BsYWluIn0.eyJoZWxsbyI6ICJ3b3JsZCJ9.McDgk0h4mRdhPM0yDUtFG_omRUwwqVS2_679Yeivj-a7l6bHs_ahWiKl1KoX_hU_";

            //when
            string test = Jwt.Decode(token, shaKey);

            //then
            Assert.AreEqual(@"{""hello"": ""world""}", test);
        }
        public void DecodeHS256()
        {
            //given
            string token = "eyJhbGciOiJIUzI1NiIsImN0eSI6InRleHRcL3BsYWluIn0.eyJoZWxsbyI6ICJ3b3JsZCJ9.chIoYWrQMA8XL5nFz6oLDJyvgHk2KA4BrFGrKymjC8E";

            //when
            string test = Jwt.Decode(token, shaKey);

            //then
            Assert.AreEqual(@"{""hello"": ""world""}", test);
        }
        public void DecodeRS512()
        {
            //given
            string token = "eyJhbGciOiJSUzUxMiIsImN0eSI6InRleHRcL3BsYWluIn0.eyJoZWxsbyI6ICJ3b3JsZCJ9.KP_mwCVRIxcF6ErdrzNcXZQDFGcL-Hlyocc4tIl3tJfzSfc7rz7qOLPjHpZ6UFH1ncd5TlpRc1B_pgvY-l0BNtx_s7n_QA55X4c1oeD8csrIoXQ6A6mtvdVGoSlGu2JnP6N2aqlDmlcefKqjl_Z-8nwDMGTMkDNhHKfHlIb2_Dliwxeq8LmNMREEdvNH2XVp_ffxBjiaKv2Eqbwc6I17241GCEmjDCvnagSgjX_5uu-da2H7TK2gtPJYUo8r9nzC7uzZJ5SB8suZH0COSofsP-9wvH0FESO40evCyEBylqg3bh9M9dIzeq8_bdTiC5kG93Fal44OEY8_Zm88wB_VjQ";

            //when
            string test = Jwt.Decode(token, PublicKey.Load(publicKey));

            //then
            Assert.AreEqual(test, @"{""hello"": ""world""}");
        }
        public void DecodeRS384()
        {
            //given
            string token = "eyJhbGciOiJSUzM4NCIsImN0eSI6InRleHRcL3BsYWluIn0.eyJoZWxsbyI6ICJ3b3JsZCJ9.cOPca7YEOxnXVdIi7cJqfgRMmDFPCrZG1M7WCJ23U57rAWvCTaQgEFdLjs7aeRAPY5Su_MVWV7YixcawKKYOGVG9eMmjdGiKHVoRcfjwVywGIb-nuD1IBzGesrQe7mFQrcWKtYD9FurjCY1WuI2FzGPp5YhW5Zf4TwmBvOKz6j2D1vOFfGsogzAyH4lqaMpkHpUAXddQxzu8rmFhZ54Rg4T-jMGVlsdrlAAlGA-fdRZ-V3F2PJjHQYUcyS6n1ULcy6ljEOgT5fY-_8DDLLpI8jAIdIhcHUAynuwvvnDr9bJ4xIy4olFRqcUQIHbcb5-WDeWul_cSGzTJdxDZsnDuvg";

            //when
            string test = Jwt.Decode(token, PublicKey.Load(publicKey));

            //then
            Assert.AreEqual(test, @"{""hello"": ""world""}");
        }
        public void DecodeRS256()
        {
            //given
            string token = "eyJhbGciOiJSUzI1NiIsImN0eSI6InRleHRcL3BsYWluIn0.eyJoZWxsbyI6ICJ3b3JsZCJ9.NL_dfVpZkhNn4bZpCyMq5TmnXbT4yiyecuB6Kax_lV8Yq2dG8wLfea-T4UKnrjLOwxlbwLwuKzffWcnWv3LVAWfeBxhGTa0c4_0TX_wzLnsgLuU6s9M2GBkAIuSMHY6UTFumJlEeRBeiqZNrlqvmAzQ9ppJHfWWkW4stcgLCLMAZbTqvRSppC1SMxnvPXnZSWn_Fk_q3oGKWw6Nf0-j-aOhK0S0Lcr0PV69ZE4xBYM9PUS1MpMe2zF5J3Tqlc1VBcJ94fjDj1F7y8twmMT3H1PI9RozO-21R0SiXZ_a93fxhE_l_dj5drgOek7jUN9uBDjkXUwJPAyp9YPehrjyLdw";

            //when
            string test = Jwt.Decode(token, PublicKey.Load(publicKey));

            //then
            Assert.AreEqual(test, @"{""hello"": ""world""}");
        }
        public void DecodeHS512()
        {
            //given
            string token = "eyJhbGciOiJIUzUxMiIsImN0eSI6InRleHRcL3BsYWluIn0.eyJoZWxsbyI6ICJ3b3JsZCJ9.9KirTNe8IRwFCBLjO8BZuXf3U2ZVagdsg7F9ZsvMwG3FuqY9W0vqwjzPOjLqPN-GkjPm6C3qWPnINhpr5bEDJQ";

            //when
            string test = Jwt.Decode(token, shaKey);

            //then
            Assert.AreEqual(@"{""hello"": ""world""}", test);
        }
Example #11
0
        public static Guid CurrentUserId()
        {
            string cookie = HttpContext.Current.Request.Cookies["_Autorize"].Value;
            Dictionary <string, object> claims = Jwt.Decode(cookie);
            object id;

            if (claims.TryGetValue("id", out id))
            {
                return(Guid.Parse(id.ToString()));
            }
            return(Guid.NewGuid());
        }
        public void DecodePlaintext()
        {
            //given
            string token = "eyJhbGciOiJub25lIn0.eyJoZWxsbyI6ICJ3b3JsZCJ9.";

            //when
            string test = Jwt.Decode(token, null);

            Debug.WriteLine("test = {0}", test);

            //then
            Assert.AreEqual(@"{""hello"": ""world""}", test);
        }
        public void EncodeRS256()
        {
            //given
            string json = @"{""hello"": ""world""}";

            //when
            string test = Jwt.Encode(json, JwsAlgorithms.RS256, PrivateKey.Load(privateKey));

            //then
            Debug.WriteLine("RS256 = {0}", test);

            Assert.AreEqual(test, "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJoZWxsbyI6ICJ3b3JsZCJ9.M3uJ9g4_e_lCyd0LtSJuSPMHe_s0Bj6LDA2kqf041SA3Les8aUmRQGlkG3ng63Thw6q06hF6r5bXX8tamku8AOyc45TIfPY9caNKKcVJ6RtXBxRWSY3r3Uh9o5zg3EOElfMWuekz0jfVfOaRgMO358ARsKW5BY6jfgmKsVyG1n3uYm8ESpzPlWWLcgUEjUSq3_m5t-COKySXa_zPPtFnA__159kSKCQRm4OcbYWzJD3-xl2i2GRQFLP7npLAuGPv42t5zf8snJvBWbROsdvvs7qzZ5v6bJy8wuBe9mGXmnbRsMFCzooZQ4H8LFrSnT3DakPVdLcDWE5HxZ-Ikr9l0A");
            Assert.AreEqual(Jwt.Decode(test, PublicKey.Load(publicKey)), json);
        }
        public void EncodeRS512()
        {
            //given
            string json = @"{""hello"": ""world""}";

            //when
            string test = Jwt.Encode(json, JwsAlgorithms.RS512, PrivateKey.Load(privateKey));

            //then
            Debug.WriteLine("RS512 = {0}", test);

            Assert.AreEqual(test, "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9.eyJoZWxsbyI6ICJ3b3JsZCJ9.YJ_5bDkZUgZj1ZoyTbSeYerUnahjt4Llbj6IwUQUY-zH_mMpywJHs2IT8wteUyX32lCCGr4NfNKpkC-zMMq7aDsklSKIg8sdGYDMheGsEw9YD0QRBF1Ovt4yuSZjWsgmdGSapXKc8CBqSzPCr9S1Rns8YhVHAYMfzHrahXuroYK35gVPQKKLbYQGcwnhpgvxMx0EfGyFbSc6r6XYK-fJ5lSqBh4wSxVMBy_5CkTVWpmnDjRuycE_j4c-yuTYUEAsj5o0sW2ahPf8aomBUC5I1ZG2yTAz8BX7dud6s2VPJQRRsUKlMNrUcMGEooJMoL_vmek9z3t_z9KFyyVHuY5XUA");
            Assert.AreEqual(Jwt.Decode(test, PublicKey.Load(publicKey)), json);
        }
        public void EncodeRS384()
        {
            //given
            string json = @"{""hello"": ""world""}";

            //when
            string test = Jwt.Encode(json, JwsAlgorithms.RS384, PrivateKey.Load(privateKey));

            //then
            Debug.WriteLine("RS384 = {0}", test);

            Assert.AreEqual(test, "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzM4NCJ9.eyJoZWxsbyI6ICJ3b3JsZCJ9.Tsq02ZIAOOK8ck0NS7VJ2NOmL6VpATGTb5hVUQC9_DJqiyrp2Vs8KGw9ahRjvIQMElkcFuWRPg-MGgHd7XUPVbhm7jK3cBvQ4y9hal6VNFfsL_DWhijLYgFpBj2nEw_qqZbChrPNRn-B1BrMKuRHOqu-7D3PPPMv9hvSg80WOLlkOUgIhp3a64saPJ8rDEibowdNNXw0k0H2i1D6WLK59Ew-6v6qO8OI9bkVc7SDV9qZSx3n0hm_JfyZbkCb-KKacJnkfVcnlNIRXRbk7cdlp90uYJ1aJDZrcIVTUOOAHQCQ4uaGwxhmH_NNHiY-sjWybP7xQCSq-Ip0yNVstWfUTQ");
            Assert.AreEqual(Jwt.Decode(test, PublicKey.Load(publicKey)), json);
        }
Example #16
0
    public static Dictionary <string, object> Decode(System.Web.HttpContext context, string secret = null)
    {
        String token = context.Authorization();

        if (token == null)
        {
            token = context.Request.QueryString.Get(".jwt");
        }
        if (token == null)
        {
            token = context.Request.Cookies.Get(".jwt")?.Value;
        }
        return(Jwt.Decode(token, secret));
    }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext.Request.Cookies["_Autorize"] == null)
            {
                return(false);
            }

            string jwt = httpContext.Request.Cookies["_Autorize"].Value;

            if (String.IsNullOrEmpty(jwt))
            {
                return(false);
            }

            Dictionary <string, object> claims = Jwt.Decode(jwt);

            if (claims == null)
            {
                return(false);
            }

            if (Jwt.Check(claims, this.Role, null))
            {
                string[] base_path = httpContext.Request.Url.AbsolutePath.ToString().Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

                string controller = String.Empty;
                string action     = "";

                if (base_path.Length == 0)
                {
                    controller = "roulet";
                }
                else
                {
                    controller = base_path[0];
                    action     = base_path[1];
                }

                object user_access_level;

                if (!claims.TryGetValue("access_level", out user_access_level))
                {
                    return(false);
                }

                if ((controller == "roulet") && (Convert.ToInt32(user_access_level) == 0 ||
                                                 Convert.ToInt32(user_access_level) == 1 ||
                                                 Convert.ToInt32(user_access_level) == 2))

                {
                    return(true);
                }
                else if ((controller == "games") &&
                         (Convert.ToInt32(user_access_level) == (int)AccessLevel.Admin))
                {
                    return(true);
                }
                else if ((controller == "logs") && (Convert.ToInt32(user_access_level) == 3))
                {
                    return(true);
                }
                else if ((controller == "users") && (Convert.ToInt32(user_access_level) == 3))
                {
                    return(true);
                }

                else if ((controller == "roulet" && action == "managepoints"))
                {
                    return(true);
                }

                else if ((controller == "games" && action == "managepoints"))
                {
                    return(true);
                }



                return(false);
            }


            return(true);
        }