private void GetToken()
        {
            try
            {
                if ((tokenExpirationTime - DateTime.Now.ToUniversalTime() < new TimeSpan(0, 2, 0)) ||
                    assertion == null)
                {
                    tokenExpirationTime = DateTime.Now.ToUniversalTime().AddHours(1);

                    var webToken = new JsonWebToken(
                        _appPrincipalId,
                        _tenantContextId.ToString(CultureInfo.InvariantCulture),
                        (new Uri(_stsUrl)).DnsSafeHost,
                        JWTTokenHelper.AcsPrincipalId,
                        DateTime.Now.ToUniversalTime(),
                        60 * 60);

                    // webToken.NameIdentifier = string.Format("{0}@{1}", appPrincipalId, tenantContextId);

                   // You can get ACS token using Asymmetric Key as well. Here would be the implementation.
                   // X509Certificate2 clientCertificate = new X509Certificate2(clientCertificateFilePath, clientCertificatePassword, X509KeyStorageFlags.Exportable);
                   // assertion = JWTTokenHelper.GenerateAccessToken(webToken, clientCertificate);

                    // Get ACS token using symmetricKey
                    assertion = JWTTokenHelper.GenerateAssertion(webToken, _symmetricKey);

                    string resource = String.Format("{0}/{1}@{2}", _protectedResourcePrincipalId, _protectedResourceHostName, _tenantContextId);
                    assertion = JWTTokenHelper.GetOAuthAccessTokenFromACS(_stsUrl, assertion, resource);
                }
            }
            catch (WebException webExc)
            {
                if (webExc.Response != null)
                {
                    using (Stream responseStream = webExc.Response.GetResponseStream())
                    {
                        StreamReader sr = new StreamReader(responseStream);
                        string responseMessage = sr.ReadToEnd();
                    }
                }
                throw;
            }
        }
        /// <summary>
        /// Generate access token with a symmetric signing key.
        /// </summary>
        /// <param name="webToken">JSON web token.</param>
        /// <param name="signingKey">Symmetric signing key.</param>
        /// <returns>Self signed assertion.</returns>
        public static string GenerateAssertion(JsonWebToken webToken, string signingKey)
        {
            TokenHeader tokenHeaderContract = new TokenHeader("HS256", String.Empty);

            string tokenHeader = Base64Utils.Encode(tokenHeaderContract.EncodeToJson());
            string tokenBody = Base64Utils.Encode(webToken.EncodeToJson());
            string rawToken = string.Format("{0}.{1}", tokenHeader, tokenBody);

            string signature = Base64Utils.Encode(JWTTokenHelper.SignData(signingKey, rawToken));

            string accessToken = string.Format(
                "{0}.{1}",
                rawToken,
                signature);

            return accessToken;
        }
 /// <summary>
 /// Generates a serialized access token using the web token that is passed.
 /// Bearer {Header}.{Body}.Thumbprint
 /// All the 3 components are Base64 encoded individually.
 /// Since a lot of cryptography is performed here, this function will be CPU intensive
 /// </summary>
 /// <param name="webToken">Json Web Security Token</param>
 /// <param name="signingCert">Signing certificate.</param>
 /// <returns>OAuth bearer token (self-signed).</returns>
 public static string GenerateAccessToken(
     JsonWebToken webToken, X509Certificate2 signingCert)
 {
     return String.Format(
         "{0}{1}",
         JWTTokenHelper.BearerTokenPrefix,
         JWTTokenHelper.GenerateAssertion(webToken, signingCert));
 }
        /// <summary>
        /// Generates a self-signed assertion.
        /// </summary>
        /// <param name="webToken">Json web token.</param>
        /// <param name="signingCert">Signing certificate.</param>
        /// <returns>Self signed assertion.</returns>
        public static string GenerateAssertion(
            JsonWebToken webToken, X509Certificate2 signingCert)
        {
            string encodedHash = Base64Utils.Encode(signingCert.GetCertHash());

            TokenHeader tokenHeaderContract = new TokenHeader("RS256", encodedHash);

            string tokenHeader = Base64Utils.Encode(tokenHeaderContract.EncodeToJson());
            string tokenBody = Base64Utils.Encode(webToken.EncodeToJson());
            string rawToken = string.Format("{0}.{1}", tokenHeader, tokenBody);
            string hash = Base64Utils.Encode(JWTTokenHelper.SignData(signingCert, rawToken));

            string accessToken = string.Format(
                "{0}.{1}",
                rawToken,
                hash);

            return accessToken;
        }