public string ValidateToken(string token, out bool status)
 {
     try
     {
         status = true;
         return(JWT.Decode(token, Secret, JwsAlgorithm.HS256));
     }
     catch (Exception)
     {
         status = false;
         return("");
     }
 }
Exemple #2
0
        public void Decode_JweEncryption_Alias()
        {
            //given
            string token = "eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2X0FMSUFTIn0.O1GahcMJNBaTEgPeOPzjm-FistaXkzmdZMPB0YkJoI6X1KIc43HJjLH28njXLQ-mGKblEhJwyFar4yfyrV9bzRSxe9K7RNDuG31m83D9yo-A2Mx1FZtvSUwm5yT62Xk0-BuZOq6S3algXvgTQie1MGRuSED-a6xmRj5RcEpop5JdEXnnlwCrn4qZt9jQpT_Ag_URgkNyuBJG878MXjArxU9Ci5WS1a-tcOgCtd33JOiCvniIBQBPFdyoz7vGZi3Y7EGhY-6T6dxyeL-_MMbkl_60HlTPrd6exfZ3c_0ofwSgvua_gAdSEN4inJWxJjH2yXiR0Ylj_lXAq_la3xFAhA.R2kyFSctYUZgIYJrUTWl8Q.LS4PGAa0bE-OyshBxUh5XhFvquKffEsSmEVU_LxSRAQ.hDDEkppjnfWUv_jKUcA6DQ";

            //when
            string json = JWT.Decode(token, PrivKey(), settings: new JwtSettings().RegisterJweAlias("A128CBC-HS256_ALIAS", JweEncryption.A128CBC_HS256));

            //then
            Console.Out.WriteLine("json = {0}", token);

            Assert.Equal(json, @"{""hello"":""world""}");
        }
Exemple #3
0
        public bool ValidateToken(string token)
        {
            try
            {
                CurrentUser = JWT.Decode <CurrentUserDTO>(token, Encoding.UTF8.GetBytes(_jwtKey));
            }
            catch
            {
                return(false);
            }

            return(CurrentUser != null);
        }
        public async Task <SankeyResponse> Transactions()
        {
            var accessToken = JWT.Decode <AccessToken>(this.Request.Cookies["jwt"], this.settings.EncryptKey, JwsAlgorithm.HS256);

            using (var client = new MonzoClient(accessToken.Value, this.settings.BaseUrl, this.settings.ApiSubDomain))
            {
                var accounts = await client.GetAccounts();

                var transactions = await client.GetTransactions(accounts.Where(x => !x.Closed).Select(x => x.ID).ToArray(), DateTime.Now.AddMonths(-1), DateTime.Now);

                return(this.transactionService.GetSankeyDataForTransactions(transactions));
            }
        }
Exemple #5
0
        public void Decode_JweAlgorithm_Alias()
        {
            //given
            string token = "eyJhbGciOiJSU0ExXzVfQUxJQVMiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.dMCd2RbBtGBb9QwpJ0lYbJ0zv5Nagl5SPwRhrJTlXTDWJ6s-Ztz0-SEOi_gXx0SxXGA2iy5gY3x2uWbi-TSZvBuNyATYqoHlPLTCvNW47_INL8Gw46VcNu54urKadPh01Agk9WajBBlx9fnGgQMw5F9YNZbo8LfUNbGnZDYaxB3Vbyhn1Q9j3X8cT2MfzQ0uEhqr4FTx12oCd-6rZXXHhGnfdOKJGaihGLf10JVJcGXwBVY4AghEcAsii0JJrk35kLjBnzfsjlb2pB1r7k_tI6_1g06-5ubz_oEtlwGBM9OeqYnTk66A4a8vUSzqEC9e3bEQbWwz94Qv2qO5r9dy5Q.Axsj29AR41DivbI_MwHVtg.OMQpAiDkqJsZo53bSz9XmKwzqnLBqI7MR7mp0NazAqI.V_t4NP94yJyKAUmeTgrysQ";

            //when
            string json = JWT.Decode(token, PrivKey(), settings: new JwtSettings().RegisterJwaAlias("RSA1_5_ALIAS", JweAlgorithm.RSA1_5));

            //then
            Console.Out.WriteLine("json = {0}", json);

            Assert.Equal(json, @"{""hello"":""world""}");
        }
Exemple #6
0
        public static bool VerificaToken(string token)
        {
            string json = JWT.Decode(token, _secretKey);

            Dictionary <string, string> payloadValues = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);

            if (payloadValues.ContainsKey("exp") && !String.IsNullOrEmpty(payloadValues["exp"].ToString()))
            {
                double agora    = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
                double expToken = double.Parse(payloadValues["exp"], System.Globalization.CultureInfo.InvariantCulture);
            }
            return(true);
        }
        public static string Decrypt(this string encrypted,
                                     string privateKey,
                                     string alg = "RSA-OAEP",
                                     string enc = "A256GCM")
        {
            var(jweAlgorithm, jweEncryption) = GetSupported(alg, enc);

            var decrypted = JWT.Decode(encrypted,
                                       privateKey.ConvertToRsa(),
                                       jweAlgorithm,
                                       jweEncryption);

            return(decrypted);
        }
        public UserLoginModel VerifyAccessToken(string accesToken)
        {
            try {
                UserLoginModel user_login = new UserLoginModel();
                DataTable      dt         = new DataTable();
                JWTPayload     payload    = JWT.Decode <JWTPayload>(accesToken, this.secretKey);
                if (payload == null)
                {
                    return(null);
                }
                if (payload.exp < DateTime.UtcNow)
                {
                    return(null);
                }

                string sql = " select PkAdminweb.admin_ID, " +
                             " PkAdminweb.name, " +
                             " PkAdminweb.admin_level_id, " +
                             " PkAdminweb.Terncode,  " +
                             " PkAdminweb.Ternsubcode," +
                             " PkDepartments.DeptName, " +
                             " PkAdminweb.adminname , " +
                             " PkAdminweb.Custom " +
                             " from PkAdminweb  " +
                             " left join PkAdminweb_level on PkAdminweb.admin_level_id = PkAdminweb_level.admin_level_id " +
                             " left join PkDepartments on PkAdminweb.Ternsubcode = PkDepartments.DeptID and PkAdminweb.Terncode = PkDepartments.CompanyID " +
                             " where (PkAdminweb.adminname = '" + payload.username + "' )";

                dt = dabase.QueryDataTable(sql);

                user_login = (from c in dt.AsEnumerable()
                              select new UserLoginModel
                {
                    AdminId = Convert.ToInt32(c["admin_ID"]),
                    name = c["name"].ToString(),
                    AdminLevel = Convert.ToInt32(c["admin_level_id"]),
                    Aminname = c["adminname"].ToString(),
                    CommanyName = c["DeptName"].ToString(),
                    CompanyID = c["Terncode"].ToString(),
                    DeptID = c["Ternsubcode"].ToString(),
                    Custom = c["Custom"].ToString()
                }).SingleOrDefault();

                return(user_login);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Exemple #9
0
        public void Decode_IKeyManagement_Override()
        {
            //given
            MockKeyManagement keyMgmt = new MockKeyManagement();
            string            token   = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..yVi-LdQQngN0C5WS.1McwSmhZzAtmmLp9y-OdnJwaJFo1nj_4ashmzl2LhubGf0Jl1OTEVJzsHZb7bkup7cGTkuxh6Vfv10ljHsjWf_URXoxP3stQqQeViVcuPV0y2Q_WHYzTNGZpmHGe-hM6gjDhyZyvu3yeXGFSvfPQmp9pWVOgDjI4RC0MQ83rzzn-rRdnZkznWjbmOPxwPrR72Qng0BISsEwbkPn4oO8-vlHkVmPpuDTaYzCT2ZR5K9JnIU8d8QdxEAGb7-s8GEJ1yqtd_w._umbK59DAKA3O89h15VoKQ";

            //when
            string json = JWT.Decode(token, aes128Key, settings: new JwtSettings().RegisterJwa(JweAlgorithm.DIR, keyMgmt));

            //then
            Console.Out.WriteLine("json = {0}", json);

            Assert.Equal(json, @"{""exp"":1392548520,""sub"":""alice"",""nbf"":1392547920,""aud"":[""https:\/\/app-one.com"",""https:\/\/app-two.com""],""iss"":""https:\/\/openid.net"",""jti"":""0e659a67-1cd3-438b-8888-217e72951ec9"",""iat"":1392547920}");
            Assert.True(keyMgmt.UnwrapCalled);
        }
Exemple #10
0
        /// <summary>VerifyResult</summary>
        /// <param name="testLabel">string</param>
        /// <param name="jwt">string</param>
        /// <param name="key">object</param>
        /// <param name="alg">JwsAlgorithm?</param>
        private static void VerifyResult(string testLabel, string jwt, object key, JwsAlgorithm?alg = null)
        {
            MyDebug.OutputDebugAndConsole(testLabel, "Original:" + jwt);

            MyDebug.InspectJwt(testLabel, jwt);

            if (alg.HasValue)
            {
                MyDebug.OutputDebugAndConsole(testLabel, "Decoded:" + JWT.Decode(jwt, key, alg.Value));
            }
            else
            {
                MyDebug.OutputDebugAndConsole(testLabel, "Decoded:" + JWT.Decode(jwt, key));
            }
        }
Exemple #11
0
        public async Task <TPayload> Verify <TPayload>(string token) where TPayload : TokenPayload
        {
            try
            {
                var keyBytes = Convert.FromBase64String(_configuration.Key);

                var decode = JWT.Decode <TPayload>(token, keyBytes);

                return(decode);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Can not verify token");
            }
        }
Exemple #12
0
        public string Get(string token)
        {
            string json = JWT.Decode(token, Base64Url.Decode("secert"), JwsAlgorithm.HS256);

            var headers = Jose.JWT.Headers(token);
            var payload = Jose.JWT.Payload(token);

            //step 1b: lookup validation key based on header info

            JObject Robj = JObject.Parse(json);
            var     aa   = Robj["sub"];

            //ActionExecutingContext
            return("value");
        }
Exemple #13
0
        /// <summary>
        /// Decrypts a blob of data encrypted using <see cref="EncryptAndSign"/> after verifying the digital signature on it.
        /// </summary>
        /// <param name="container"></param>
        /// <param name="joseObject">The compact form of the encrypted and signed JOSE object.</param>
        /// <param name="signedBy">The certificate of the signer will be output into this variable.</param>
        /// <param name="decryptionCertificates">The set of certificates whose key pairs may be used for decryption. The correct certificate and key pair will be selected automatically (if it is among the set).</param>
        /// <exception cref="CryptographicException">
        /// Thrown if a cryptographic operation fails (e.g. because you do not have the correct decryption key).
        /// </exception>
        public static byte[] VerifyAndDecrypt(this HelpersContainerClasses.Jose container, string joseObject, out X509Certificate2 signedBy, params X509Certificate2[] decryptionCertificates)
        {
            Helpers.Argument.ValidateIsNotNull(joseObject, nameof(joseObject));
            Helpers.Argument.ValidateIsNotNull(decryptionCertificates, nameof(decryptionCertificates));

            foreach (var decryptionCertificate in decryptionCertificates)
            {
                if (decryptionCertificate == null)
                {
                    throw new ArgumentException("Decryption certificate list cannot contain null values.", nameof(decryptionCertificates));
                }

                VerifyCertificateAndPrivateKeyIsSaneAndUsable(decryptionCertificate);
            }

            // Part 1: verify signature.
            var signedHeader = JWT.Headers(joseObject);

            if (!signedHeader.ContainsKey("typ") || signedHeader["typ"] as string != JoseSignedType)
            {
                throw new ArgumentException("The JOSE object was not produced by " + nameof(EncryptAndSign), nameof(joseObject));
            }

            signedBy = GetCertificateFromJoseHeader(signedHeader);

            VerifyCertificateIsSaneAndUsable(signedBy);

            var encrypted = JWT.Decode(joseObject, signedBy.GetRSAPublicKey(), JwsAlgorithm.RS512);

            // Part 2: decrypt.
            var encryptedHeader = JWT.Headers(encrypted);

            if (!encryptedHeader.ContainsKey("typ") || encryptedHeader["typ"] as string != JoseEncryptedType)
            {
                throw new ArgumentException("The JOSE object was not produced by " + nameof(EncryptAndSign), nameof(joseObject));
            }

            var encryptedFor = GetCertificateFromJoseHeader(encryptedHeader);

            var decryptWith = decryptionCertificates.FirstOrDefault(c => c.Thumbprint == encryptedFor.Thumbprint);

            if (decryptWith == null)
            {
                throw new CryptographicException("None of the available decryption keys matched the one used to encrypt the JOSE object.");
            }

            return(JWT.DecodeBytes(encrypted, decryptWith.GetRSAPrivateKey(), JweAlgorithm.RSA_OAEP, JweEncryption.A256CBC_HS512));
        }
Exemple #14
0
        internal static void VerifyTokenSignature(string JwsJson, JObject jwk)
        {
            if ("EC".Equals(jwk["kty"].ToString()))
            {
                byte[] x = Base64Url.Decode(jwk["x"].ToString());
                byte[] y = Base64Url.Decode(jwk["y"].ToString());

#if (NETCOREAPP2_1 || NETSTANDARD2_0)
                var publicKey = ECDsa.Create(new ECParameters
                {
                    Curve = ECCurve.NamedCurves.nistP256,
                    Q     = new ECPoint
                    {
                        X = x,
                        Y = y
                    },
                    D = null
                });

                var decoded = JWT.Decode(JwsJson, publicKey);
#else
                CngKey cngKey  = EccKey.New(x, y);
                var    decoded = JWT.Decode(JwsJson, cngKey);
#endif
                return;
            }
            else if ("RSA".Equals(jwk["kty"].ToString()))
            {
                byte[] n = Base64Url.Decode(jwk["n"].ToString());
                byte[] e = Base64Url.Decode(jwk["e"].ToString());

                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    RSAParameters rsaParameters = new RSAParameters
                    {
                        Exponent = e,
                        Modulus  = n
                    };
                    RSA.ImportParameters(rsaParameters);
                    JWT.Decode(JwsJson, RSA);
                    return;
                }

                /*var publicKey = RsaKey.New(e, n);
                 * var decoded = JWT.Decode(JwsJson, publicKey);
                 * return;*/
            }
        }
Exemple #15
0
        public Token Decode(string clientToken)
        {
            var    token   = new Token();
            string decoded = JWT.Decode(clientToken, this.Key);
            var    dto     = JsonConvert.DeserializeObject <Dictionary <string, string> >(decoded);

            token.ClientToken = clientToken;

            foreach (var c in dto)
            {
                switch (c.Key)
                {
                //case "aud":
                //    token.Audience = c.Value;
                //    break;
                case "iat":
                    token.CreatedOn = new DateTime(c.Value.To <long>(), DateTimeKind.Utc);
                    break;

                case "exp":
                    token.ExpiresOn = new DateTime(c.Value.To <long>(), DateTimeKind.Utc);
                    break;

                case "sub":
                    token.Subject = c.Value;
                    break;

                //case "jti":
                //    token.TokenId = c.Value;
                //    break;
                case "iss":
                    token.IssuedBy = c.Value;
                    break;

                case "loginid":
                    token.LoginId = c.Value.To <long>();
                    break;
                    //case "userid":
                    //    token.UserId = c.Value.To<int>();
                    //    break;
                    //case "officeid":
                    //    token.OfficeId = c.Value.To<int>();
                    //    break;
                }
            }

            return(token);
        }
Exemple #16
0
        public void Decode_ICompression_Override()
        {
            //given
            MockCompression compress = new MockCompression();

            string token = "eyJhbGciOiJSU0EtT0FFUCIsInppcCI6IkRFRiIsImVuYyI6IkExMjhDQkMtSFMyNTYifQ.nXSS9jDwE0dXkcGI7UquZBhn2nsB2P8u-YSWEuTAgEeuV54qNU4SlE76bToI1z4LUuABHmZOv9S24xkF45b7Mrap_Fu4JXH8euXrQgKQb9o_HL5FvE8m4zk5Ow13MKGPvHvWKOaNEBFriwYIfPi6QBYrpuqn0BaANc_aMyInV0Fn7e8EAgVmvoagmy7Hxic2sPUeLEIlRCDSGa82mpiGusjo7VMJxymkhnMdKufpGPh4wod7pvgb-jDWasUHpsUkHqSKZxlrDQxcy1-Pu1G37TAnImlWPa9NU7500IXc-W07IJccXhR3qhA5QaIyBbmHY0j1Dn3808oSFOYSF85A9w.uwbZhK-8iNzcjvKRb1a2Ig.jxj1GfH9Ndu1y0b7NRz_yfmjrvX2rXQczyK9ZJGWTWfeNPGR_PZdJmddiam15Qtz7R-pzIeyR4_qQoMzOISkq6fDEvEWVZdHnnTUHQzCoGX1dZoG9jXEwfAk2G1vXYT2vynEQZ72xk0V_OBtKhpIAUEFsXwCUeLAAgjFNY4OGWZl_Kmv9RTGhnePZfVbrbwg.WuV64jlV03OZm99qHMP9wQ";

            //when
            string json = JWT.Decode(token, PrivKey(), settings: new JwtSettings().RegisterCompression(JweCompression.DEF, compress));

            //then
            Console.Out.WriteLine("json = {0}", json);

            Assert.Equal(json, @"{""exp"":1392963710,""sub"":""alice"",""nbf"":1392963110,""aud"":[""https:\/\/app-one.com"",""https:\/\/app-two.com""],""iss"":""https:\/\/openid.net"",""jti"":""9fa7a38a-28fd-421c-825c-8fab3bbf3fb4"",""iat"":1392963110}");
            Assert.True(compress.DecompressCalled);
        }
Exemple #17
0
        public static void createEncryptionToken()
        {
            var payload = new Dictionary <string, object>()
            {
                { "sub", "*****@*****.**" },
                { "exp", 1300819380 }
            };

            var    publicKey = new X509Certificate2(clientCert, "1234%%abcd").PublicKey.Key as RSACryptoServiceProvider;
            string token     = JWT.Encode(payload, publicKey, JweAlgorithm.RSA_OAEP, JweEncryption.A256GCM);

            var    privateKey = new X509Certificate2(clientCert, "1234%%abcd", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider;
            string json       = JWT.Decode(token, privateKey);

            Console.WriteLine(json);
        }
Exemple #18
0
        /// <summary>
        /// Decode the JWT format string
        /// </summary>
        /// <param name="token">The encoded string token in JWT format</param>
        /// <returns>String</returns>
        private static string decodeJWT(string data)
        {
            string result    = "";
            var    secretKey = "Super";

            byte[] bytesKey = Encoding.ASCII.GetBytes(secretKey);
            try
            {
                result = JWT.Decode(data, bytesKey);
            }
            catch (Exception e)
            {
                return(null);
            }
            return(result);
        }
Exemple #19
0
        public async Task <string> GetBricksetApiKey(Identification allMyBricksIdentification)
        {
            var client = new FlurlClient().Configure(settings => settings.HttpClientFactory = new HmacDelegatingHandlerHttpClientFactory());

            var apiKeyRequest = allMyBricksIdentification.ToApiKeyRequest();

            apiKeyRequest.KeyOption = RandomKeyOptionGenerator.GetRandomKeyOption();

            var responseApiKeyResult = await _allMyBricksOnboardingApiKeyServiceUrl
                                       .AppendPathSegment(Constants.AllMyBricksOnboardingApiKeyServiceBricksetMethod)
                                       .WithClient(client)
                                       .PostJsonAsync(apiKeyRequest)
                                       .ReceiveString().ConfigureAwait(false);

            return(JWT.Decode(responseApiKeyResult, Encoding.UTF8.GetBytes(allMyBricksIdentification.RegistrationHash.ToCharArray()), (JwsAlgorithm)apiKeyRequest.KeyOption));
        }
Exemple #20
0
        public JwtToken DecodeToken(string token)
        {
            try
            {
                var      publicKey     = new X509Certificate2(_configuration["TokenSigningCertificatePath"]).PublicKey.Key as RSACryptoServiceProvider;
                string   verifiedToken = JWT.Decode(token, publicKey);
                JwtToken decodedToken  = JsonConvert.DeserializeObject <JwtToken>(verifiedToken);

                return(decodedToken);
            }

            catch (Exception ex)
            {
                throw;
            }
        }
Exemple #21
0
        public void Decode_IJwsAlgorithm_Override()
        {
            //given
            MockJwsAlgorithm jwsAlg = new MockJwsAlgorithm();

            string token = "eyJhbGciOiJub25lIn0.eyJoZWxsbyI6ICJ3b3JsZCJ9.";

            //when
            var test = JWT.Decode <IDictionary <string, object> >(token, settings: new JwtSettings().RegisterJws(JwsAlgorithm.none, jwsAlg));

            //then
            Assert.Equal(test, new Dictionary <string, object> {
                { "hello", "world" }
            });
            Assert.True(jwsAlg.VerifyCalled);
        }
Exemple #22
0
        public string CheckSignatureAndDecryptJWT(string jsonToken, List <OIDCKey> OPKeys = null, string ClientSecret = null, List <OIDCKey> RPKeys = null)
        {
            Dictionary <string, object> headers = null;

            try {
                headers = (Dictionary <string, object>)JWT.Headers(jsonToken);
            }
            catch (Exception)
            {
                // No JWT in the message.
                return(jsonToken);
            }

            if (headers.ContainsKey("enc"))
            {
                string kid = (headers.ContainsKey("kid")) ? headers["kid"] as string : null;
                RSACryptoServiceProvider encKey = null;
                if (RPKeys.Count == 1)
                {
                    encKey = RPKeys[0].GetRSA();
                }
                else
                {
                    encKey = RPKeys.Find(
                        delegate(OIDCKey k)
                    {
                        return(k.Kid == kid);
                    }
                        ).GetRSA();
                }

                jsonToken = JWT.Decode(jsonToken, encKey);
                try
                {
                    headers = (Dictionary <string, object>)JWT.Headers(jsonToken);
                }
                catch (Exception)
                {
                    // No JWT in the message.
                    return(jsonToken);
                }
            }

            object sigKey = GetSignKey(headers, OPKeys, ClientSecret);

            return(JWT.Decode(jsonToken, sigKey));
        }
Exemple #23
0
        public void Encode_IJweAlgorithm_Override()
        {
            //given
            MockJweAlgorithm encAlg = new MockJweAlgorithm(128);

            string json =
                @"{""exp"":1389189552,""sub"":""alice"",""nbf"":1389188952,""aud"":[""https:\/\/app-one.com"",""https:\/\/app-two.com""],""iss"":""https:\/\/openid.net"",""jti"":""e543edf6-edf0-4348-8940-c4e28614d463"",""iat"":1389188952}";

            //when
            string token = JWT.Encode(json, aes128Key, JweAlgorithm.DIR, JweEncryption.A128GCM, settings: new JwtSettings().RegisterJwe(JweEncryption.A128GCM, encAlg));

            //then
            Console.Out.WriteLine("DIR_A128GCM = {0}", token);

            Assert.Equal(JWT.Decode(token, aes128Key), json);
            Assert.True(encAlg.EncryptCalled);
        }
Exemple #24
0
        public string GetNewToken(string token)
        {
            var decodedToken        = JWT.Decode(token, _jwtConfiguration.GetAudienceSecretBytes());
            var decodedJObjectToken = (JObject)JsonConvert.DeserializeObject(decodedToken);
            var expiryTime          = decodedJObjectToken["exp"].ToObject <double>();

            if (GetCurrentSeconds - expiryTime > _jwtConfiguration.ExpiryMinutes * 60)
            {
                return(null);
            }

            var userId = decodedJObjectToken[Claims.UserId].ToObject <int>();

            var user = _userRepository.GetUserById(userId);

            return(GetJwtTokenForUser(user));
        }
Exemple #25
0
        private string DecodeJWT(string token)
        {
            string result    = "";
            var    secretKey = "Super";

            byte[] bytesKey = Encoding.ASCII.GetBytes(secretKey);
            try
            {
                result = JWT.Decode(token, bytesKey);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Invalid token! : " + e);
                return(null);
            }
            return(result);
        }
Exemple #26
0
        internal static async Task <Dictionary <string, dynamic> > ExtractTokenContent(string token)
        {
            var key = await KeyClient.GetSecretAsync(WebConfigurationManager.AppSettings["SecretUri"]);

            var keyBytes = Encoding.UTF8.GetBytes(key.Value);

            try
            {
                var json = JWT.Decode(token, keyBytes, JwsAlgorithm.HS256);
                var dict = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(json);
                return(dict);
            }
            catch
            {
                return(null);
            }
        }
Exemple #27
0
        public bool GetIsJwtValid(string jwt)
        {
            bool result = false;

            try
            {
                byte[] key = this.Base64UrlDecode(this._clientSecret);
                JWT.Decode <IDictionary <string, object> >(jwt, key);
                result = !this.GetIsJwtExpired(jwt);
            }
            catch (Exception)
            {
                Console.WriteLine("JWT has an invalid signature");
                result = false;
            }
            return(result);
        }
Exemple #28
0
        public virtual void HandleMcpeServerToClientHandshake(McpeServerToClientHandshake message)
        {
            string token = message.token;

            if (Log.IsDebugEnabled)
            {
                Log.Debug($"JWT:\n{token}");
            }

            IDictionary <string, dynamic> headers = JWT.Headers(token);
            string x5u = headers["x5u"];

            if (Log.IsDebugEnabled)
            {
                Log.Debug($"JWT payload:\n{JWT.Payload(token)}");
            }

            var remotePublicKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(x5u.DecodeBase64());

            var signParam = new ECParameters
            {
                Curve = ECCurve.NamedCurves.nistP384,
                Q     =
                {
                    X = remotePublicKey.Q.AffineXCoord.GetEncoded(),
                    Y = remotePublicKey.Q.AffineYCoord.GetEncoded()
                },
            };

            signParam.Validate();

            var signKey = ECDsa.Create(signParam);

            try
            {
                var data = JWT.Decode <HandshakeData>(token, signKey);

                Client.InitiateEncryption(Base64Url.Decode(x5u), Base64Url.Decode(data.salt));
            }
            catch (Exception e)
            {
                Log.Error(token, e);
                throw;
            }
        }
        public static JweMessage FromEncryptedString(string b64MessageToDecrypt, List <X509Certificate2> issuerEncryptionCerts, IJweCryptoPolicy cryptoPolicy)
        {
            var parts = b64MessageToDecrypt.SplitInToSections();

            var jwsHeader = JwsHeader.CreateJweHeaderFromEncryptedHeader(parts[0]);

            var verifiedPayload = JWT.Decode(
                b64MessageToDecrypt, jwsHeader.SigningPublicCert.GetRSAPublicKey());

            return(new JweMessage
            {
                CryptoPolicy = cryptoPolicy,
                EncryptedMessage = b64MessageToDecrypt,
                Header = jwsHeader,
                Payload = JweEncryptedPayload.CreateFromEncryptedPayload(verifiedPayload, issuerEncryptionCerts),
                Signature = new JweSignature(parts[2])
            });
        }
        public static PayloadModel <T> GetPayloadByJwtToken <T>(string token)
        {
            try
            {
                var key = Convert.FromBase64String(ConfigurationHelper.JwtPublicKey);
                var mod = JWT.Decode <T>(token, key);

                return(new PayloadModel <T>
                {
                    model = mod
                });
            }
            catch (Exception ex)
            {
                //Logger.Error(ex);
                return(default(PayloadModel <T>));
            }
        }