public static IdToken Parse(string idToken)
        {
            if (string.IsNullOrEmpty(idToken))
            {
                return(null);
            }

            IdToken idTokenBody = null;

            string[] idTokenSegments = idToken.Split(new[] { '.' });

            if (idTokenSegments.Length < 2)
            {
                throw new MsalClientException(
                          MsalError.InvalidJwtError,
                          MsalErrorMessage.IDTokenMustHaveTwoParts);
            }

            try
            {
                byte[] idTokenBytes = Base64UrlHelpers.DecodeToBytes(idTokenSegments[1]);
                idTokenBody = JsonHelper.DeserializeFromJson <IdToken>(idTokenBytes);
            }
            catch (JsonException exc)
            {
                throw new MsalClientException(
                          MsalError.JsonParseError,
                          MsalErrorMessage.FailedToParseIDToken,
                          exc);
            }

            return(idTokenBody);
        }
        [InlineData("", "")]                    // Empty string
        public void DecodeToBytes_ValidBase64UrlString_ReturnsByteArray(string stringToDecode, string expectedDecodedString)
        {
            var expectedDecodedByteArray = Encoding.UTF8.GetBytes(expectedDecodedString);

            var actualDecodedByteArray = Base64UrlHelpers.DecodeToBytes(stringToDecode);

            Assert.Equal(expectedDecodedByteArray, actualDecodedByteArray);
        }
        public void DecodeToBytes_InvalidBase64UrlStringLength_ThrowsException()
        {
            var stringToDecodeWithInvalidLength = "MTIzNDU21";

            Action decodeAction = () => Base64UrlHelpers.DecodeToBytes(stringToDecodeWithInvalidLength);

            var exception = Assert.Throws <ArgumentException>(decodeAction);

            Assert.Equal(IDWebErrorMessage.InvalidBase64UrlString + " (Parameter 'arg')", exception.Message);
        }
示例#4
0
        public void DecodeToBytes_ValidBase64UrlString_ReturnsByteArray()
        {
            var stringToDecodeWithNoPadding = "MTIzNDU2";
            var expectedDecodedByteArray    = Encoding.UTF8.GetBytes("123456");

            var actualDecodedByteArray = Base64UrlHelpers.DecodeToBytes(stringToDecodeWithNoPadding);

            Assert.Equal(expectedDecodedByteArray, actualDecodedByteArray);

            var stringToDecodeWith1Padding = "MTIzNDU2Nzg";

            expectedDecodedByteArray = Encoding.UTF8.GetBytes("12345678");

            actualDecodedByteArray = Base64UrlHelpers.DecodeToBytes(stringToDecodeWith1Padding);

            Assert.Equal(expectedDecodedByteArray, actualDecodedByteArray);

            var stringToDecodeWith2Padding = "MTIzNDU2Nw";

            expectedDecodedByteArray = Encoding.UTF8.GetBytes("1234567");

            actualDecodedByteArray = Base64UrlHelpers.DecodeToBytes(stringToDecodeWith2Padding);

            Assert.Equal(expectedDecodedByteArray, actualDecodedByteArray);

            var stringToDecodeWithBase64Plus = "MTI-MTIz";

            expectedDecodedByteArray = Encoding.UTF8.GetBytes("12>123");

            actualDecodedByteArray = Base64UrlHelpers.DecodeToBytes(stringToDecodeWithBase64Plus);

            Assert.Equal(expectedDecodedByteArray, actualDecodedByteArray);

            var stringToDecodeWithBase64Slash = "MTI_MTIz";

            expectedDecodedByteArray = Encoding.UTF8.GetBytes("12?123");

            actualDecodedByteArray = Base64UrlHelpers.DecodeToBytes(stringToDecodeWithBase64Slash);

            Assert.Equal(expectedDecodedByteArray, actualDecodedByteArray);

            var emptyStringToDecode = string.Empty;

            expectedDecodedByteArray = Encoding.UTF8.GetBytes(emptyStringToDecode);

            actualDecodedByteArray = Base64UrlHelpers.DecodeToBytes(emptyStringToDecode);

            Assert.Equal(expectedDecodedByteArray, actualDecodedByteArray);
        }
示例#5
0
        public static ClientInfo CreateFromJson(string clientInfo)
        {
            if (string.IsNullOrEmpty(clientInfo))
            {
                throw new MsalClientException(
                          MsalError.JsonParseError,
                          "client info is null");
            }

            try
            {
                return(JsonHelper.DeserializeFromJson <ClientInfo>(Base64UrlHelpers.DecodeToBytes(clientInfo)));
            }
            catch (Exception exc)
            {
                throw new MsalClientException(
                          MsalError.JsonParseError,
                          "Failed to parse the returned client info.",
                          exc);
            }
        }
示例#6
0
        internal static string DecryptBrokerResponse(string encryptedBrokerResponse, ICoreLogger logger)
        {
            byte[] outputBytes = Base64UrlHelpers.DecodeToBytes(encryptedBrokerResponse);
            string plaintext   = string.Empty;

            using (MemoryStream memoryStream = new MemoryStream(outputBytes))
            {
                byte[] key = GetRawBrokerKey(logger);

                AesManaged algo = GetCryptoAlgorithm(key);
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, algo.CreateDecryptor(), CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(cryptoStream))
                    {
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

            return(plaintext);
        }
        /// <summary>
        /// Creates a <see cref="KerberosSupplementalTicket"/> object from given ID token string..
        /// </summary>
        /// <param name="idToken">ID token string.</param>
        /// <returns>A <see cref="KerberosSupplementalTicket"/> object if a Kerberos Ticket Claim exists in the given
        /// idToken parameter and is parsed correctly. Null, otherwise.</returns>
        public static KerberosSupplementalTicket FromIdToken(string idToken)
        {
            if (string.IsNullOrEmpty(idToken) || idToken.Length < 128)
            {
                // Token is empty or too short - ignore parsing.
                return(null);
            }

            string[] sections = idToken.Split('.');
            if (sections.Length != 3)
            {
                // JWT should be consists of 3 parts separated with '.'
                return(null);
            }

            // decodes the second section containing the Kerberos Ticket claim if exists.
            byte[] payloadBytes = Base64UrlHelpers.DecodeToBytes(sections[1]);
            string payload      = Encoding.UTF8.GetString(payloadBytes);

            if (string.IsNullOrEmpty(payload))
            {
                return(null);
            }

            // parse the JSON data and find the included Kerberos Ticket claim.
            JObject payloadJson = JObject.Parse(payload);
            JToken  claimValue;

            if (!payloadJson.TryGetValue(KerberosClaimType, out claimValue))
            {
                return(null);
            }

            // Kerberos Ticket claim found.
            // Parse the json and construct the KerberosSupplementalTicket object.
            string kerberosAsRep = claimValue.Value <string>();

            return((KerberosSupplementalTicket)JsonConvert.DeserializeObject(kerberosAsRep, typeof(KerberosSupplementalTicket)));
        }
示例#8
0
        public static IdToken Parse(string idToken)
        {
            if (string.IsNullOrEmpty(idToken))
            {
                return(null);
            }

            IdToken idTokenBody = null;

            string[] idTokenSegments = idToken.Split(new[] { '.' });

            if (idTokenSegments.Length < 2)
            {
                throw new MsalClientException(
                          MsalError.InvalidJwtError,
                          MsalErrorMessage.IDTokenMustHaveTwoParts);
            }

            try
            {
                byte[] idTokenBytes = Base64UrlHelpers.DecodeToBytes(idTokenSegments[1]);
                using (var stream = new MemoryStream(idTokenBytes))
                {
                    var serializer = new DataContractJsonSerializer(typeof(IdToken));
                    idTokenBody = (IdToken)serializer.ReadObject(stream);
                }
            }
            catch (Exception exc)
            {
                throw new MsalClientException(
                          MsalError.JsonParseError,
                          MsalErrorMessage.FailedToParseIDToken,
                          exc);
            }

            return(idTokenBody);
        }
        internal static string DecryptBrokerResponse(string encryptedBrokerResponse, ICoreLogger logger)
        {
            byte[] outputBytes = Base64UrlHelpers.DecodeToBytes(encryptedBrokerResponse);
            string plaintext   = string.Empty;

            if (TryGetBrokerKey(out byte[] key))
            {
                AesManaged   algo         = null;
                CryptoStream cryptoStream = null;
                MemoryStream memoryStream = null;
                try
                {
                    memoryStream = new MemoryStream(outputBytes);
                    algo         = CreateSymmetricAlgorith(key);
                    cryptoStream = new CryptoStream(
                        memoryStream,
                        algo.CreateDecryptor(),
                        CryptoStreamMode.Read);
                    using (StreamReader srDecrypt = new StreamReader(cryptoStream))
                    {
                        plaintext = srDecrypt.ReadToEnd();
                        return(plaintext);
                    }
                }
                finally
                {
                    memoryStream?.Dispose();
                    cryptoStream?.Dispose();
                    algo?.Dispose();
                }
            }

            throw new MsalClientException(
                      MsalError.BrokerKeyFetchFailed,
                      MsalErrorMessage.iOSBrokerKeyFetchFailed);
        }