コード例 #1
0
        public string CreateAssertionToken()
        {
            var now = DateTime.Now.ToUniversalTime();

            var securityKey        = new X509SecurityKey(_certificate);
            var signingCredentials = new SigningCredentials(
                securityKey,
                SecurityAlgorithms.RsaSha256
                );

            var jwt = new JwtSecurityToken(_clientId,
                                           _audience,
                                           new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Sub, _clientId),
                new Claim(JwtRegisteredClaimNames.Iat, EpochTime.GetIntDate(now).ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Integer64)
            },
                                           now,
                                           now.AddMinutes(1),
                                           signingCredentials
                                           );

            jwt.Header.Add(JwtHeaderParameterNames.X5t, securityKey.X5t);

            var tokenHandler = new JwtSecurityTokenHandler();

            return(tokenHandler.WriteToken(jwt));
        }
コード例 #2
0
        public string Generate(TimeSpan expireInInterval)
        {
            using var cngKey    = CngKey.Import(Convert.FromBase64String(_setting.PrivateKeyBody), CngKeyBlobFormat.Pkcs8PrivateBlob);
            using var algorithm = new ECDsaCng(cngKey)
                  {
                      HashAlgorithm = CngAlgorithm.ECDsaP256
                  };
            var signingCredentials = new SigningCredentials(new ECDsaSecurityKey(algorithm), SecurityAlgorithms.EcdsaSha256)
            {
                // prevent ObjectDisposedException exception when this method it's called multiple times
                CryptoProviderFactory = new CryptoProviderFactory {
                    CacheSignatureProviders = false
                }
            };

            var now   = DateTime.UtcNow;
            var exp   = now.Add(expireInInterval);
            var token = new JwtSecurityToken(
                claims: new List <Claim>
            {
                new Claim("iss", _teamId),
                new Claim("sub", _clientId),
                new Claim("aud", "https://appleid.apple.com"),
                new Claim("iat", EpochTime.GetIntDate(now).ToString(), ClaimValueTypes.Integer64),
                new Claim("exp", EpochTime.GetIntDate(exp).ToString(), ClaimValueTypes.Integer64),
            },
                signingCredentials: signingCredentials);

            token.Header.Add("kid", _setting.KeyId);

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
コード例 #3
0
ファイル: Addon.cs プロジェクト: Jvs34/Gmad.Dotnet
        internal static AddonInfo ReadAddonInfo(BinaryReader reader, char gmadFormatVersion)
        {
            ulong steamid   = reader.ReadUInt64();           //steamid
            ulong timestamp = reader.ReadUInt64();           //timestamp

            var timeUpdated = new EpochTime(( int )timestamp).DateTime;

            if (gmadFormatVersion > 1)
            {
                string content = reader.ReadBootilString();
                while (!string.IsNullOrEmpty(content))
                {
                    content = reader.ReadBootilString();
                }
            }

            string gmadTitle     = reader.ReadBootilString();
            string gmadAddonJson = reader.ReadBootilString();             //gmad reads this first then parses it later to get the actual description
            string gmadAuthor    = reader.ReadBootilString();

            int gmadAddonVersion = reader.ReadInt32();

            AddonInfo addonInfo = DeserializeAddonInfoCallback(gmadAddonJson);

            addonInfo.Title = gmadTitle;

            return(addonInfo);
        }
コード例 #4
0
        public List <SurfaceSgp4Pair> GetCoordinatePairs(Tle satalite, DateTime from, DateTime to, int resolution)
        {
            Sgp4 sgp4Propagator = new Sgp4(satalite, 1);

            var epochFrom = new EpochTime(from);
            var epochTo   = new EpochTime(to);

            var stepSize = (to - from).TotalMinutes / resolution;

            sgp4Propagator.runSgp4Cal(epochFrom, epochTo, stepSize);

            var results = sgp4Propagator.getRestults()
                          .Select((sgp, i) => {
                var time = from.AddMinutes(i * stepSize);
                return(new SurfaceSgp4Pair
                {
                    TimePointUtc = time,
                    SatalitePoint = sgp,
                    SurfacePoint = this.GetMePosition(time)
                });
            })
                          .ToList();

            return(results);
        }
コード例 #5
0
 private static void FillPayload(KeyValuePair<string, JObject> payload, JwsDescriptor descriptor)
 {
     foreach (var property in payload.Value.Properties())
     {
         switch (property.Name)
         {
             case "iat":
             case "nbf":
             case "exp":
                 descriptor.AddClaim(property.Name, EpochTime.ToDateTime((long)property.Value));
                 break;
             default:
                 if (property.Value is JArray)
                 {
                     var array = new List<string>(((JArray)property.Value).ToObject<string[]>());
                     descriptor.Audiences = array;
                 }
                 else
                 {
                     descriptor.AddClaim(property.Name, (string)property.Value);
                 }
                 break;
         }
     }
 }
コード例 #6
0
        public static (bool validToken, IIdentity Identity) ValidateToken(string tokenString)
        {
            var tokenValidationParams = new TokenValidationParameters()
            {
                ValidateLifetime         = true,
                ValidateAudience         = true,
                ValidateIssuer           = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer      = "jwtDrSim",
                ValidAudience    = "jwtDrSim",
                IssuerSigningKey = key,
            };

            try
            {
                ClaimsPrincipal claimsPrincipal = new JwtSecurityTokenHandler().ValidateToken(tokenString, tokenValidationParams, out SecurityToken securityToken);
                var             claims          = claimsPrincipal.Claims.ToList();
                long            notBefore       = long.Parse(claims.Where(i => i.Type == "nbf").First().Value);
                long            expires         = long.Parse(claims.Where(i => i.Type == "exp").First().Value);
                long            utcNow          = EpochTime.GetIntDate(DateTime.UtcNow.ToUniversalTime());

                if (expires - utcNow < 0)
                {
                    return(false, null);
                }
                return(true, claimsPrincipal.Identity);
            }
            catch
            {
                return(false, null);
            }
        }
コード例 #7
0
        public void Create()
        {
            var descriptor = new IdTokenDescriptor();

            descriptor.Algorithm      = SignatureAlgorithm.None;
            descriptor.Issuer         = "http://server.example.com";
            descriptor.Subject        = "248289761001";
            descriptor.Audience       = "s6BhdRkqt3";
            descriptor.Nonce          = "n-0S6_WzA2Mj";
            descriptor.ExpirationTime = EpochTime.ToDateTime(1311281970);
            descriptor.IssuedAt       = EpochTime.ToDateTime(1311280970);
            descriptor.AddClaim(Encoding.UTF8.GetBytes("name"), "Jane Doe");
            descriptor.GivenName  = "Jane";
            descriptor.FamilyName = "Doe";
            descriptor.Gender     = "female";
            descriptor.Birthdate  = "0000-10-31";
            descriptor.Email      = "*****@*****.**";
            descriptor.Picture    = "http://example.com/janedoe/me.jpg";

            var writer = new JwtWriter();
            var jwt    = writer.WriteTokenString(descriptor);

            Assert.Equal("eyJhbGciOiJub25lIn0.eyJpc3MiOiJodHRwOi8vc2VydmVyLmV4YW1wbGUuY29tIiwic3ViIjoiMjQ4Mjg5NzYxMDAxIiwiYXVkIjoiczZCaGRSa3F0MyIsIm5vbmNlIjoibi0wUzZfV3pBMk1qIiwiZXhwIjoxMzExMjgxOTcwLCJpYXQiOjEzMTEyODA5NzAsIm5hbWUiOiJKYW5lIERvZSIsImdpdmVuX25hbWUiOiJKYW5lIiwiZmFtaWx5X25hbWUiOiJEb2UiLCJnZW5kZXIiOiJmZW1hbGUiLCJiaXJ0aGRhdGUiOiIwMDAwLTEwLTMxIiwiZW1haWwiOiJqYW5lZG9lQGV4YW1wbGUuY29tIiwicGljdHVyZSI6Imh0dHA6Ly9leGFtcGxlLmNvbS9qYW5lZG9lL21lLmpwZyJ9.", jwt);
            //Assert.Equal("eyJhbGciOiJub25lIn0.eyJpc3MiOiJodHRwOlx1MDAyZlx1MDAyZnNlcnZlci5leGFtcGxlLmNvbSIsInN1YiI6IjI0ODI4OTc2MTAwMSIsImF1ZCI6InM2QmhkUmtxdDMiLCJub25jZSI6Im4tMFM2X1d6QTJNaiIsImV4cCI6MTMxMTI4MTk3MCwiaWF0IjoxMzExMjgwOTcwLCJuYW1lIjoiSmFuZSBEb2UiLCJnaXZlbl9uYW1lIjoiSmFuZSIsImZhbWlseV9uYW1lIjoiRG9lIiwiZ2VuZGVyIjoiZmVtYWxlIiwiYmlydGhkYXRlIjoiMDAwMC0xMC0zMSIsImVtYWlsIjoiamFuZWRvZUBleGFtcGxlLmNvbSIsInBpY3R1cmUiOiJodHRwOlx1MDAyZlx1MDAyZmV4YW1wbGUuY29tXHUwMDJmamFuZWRvZVx1MDAyZm1lLmpwZyJ9.", jwt);
        }
コード例 #8
0
ファイル: TimeHelper.cs プロジェクト: ZhenyaP/sso-service
        /// <summary>
        /// Gets the date from token timestamp.
        /// </summary>
        /// <param name="timestamp">The timestamp.</param>
        /// <returns>The date.</returns>
        public static DateTime GetDateFromTokenTimestamp(int timestamp)
        {
            var secondsAfterBaseTime =
                Convert.ToInt64(Math.Truncate(Convert.ToDouble(timestamp, CultureInfo.InvariantCulture)));

            return(EpochTime.DateTime(secondsAfterBaseTime));
        }
コード例 #9
0
        public void Build_Jws()
        {
            var builder = new JwtDescriptorBuilder();

            var now = EpochTime.ToDateTime(EpochTime.UtcNow);

            builder
            .SignWith(RsaJwk.GenerateKey(2048, true, SignatureAlgorithm.RsaSsaPssSha256))
            .IssuedBy("https://issuer.example.com")
            .ExpiresAt(now);

            var descriptor = builder.Build();

            Assert.IsType <JwsDescriptor>(descriptor);
            var jws = (JwsDescriptor)descriptor;

            Assert.Equal("https://issuer.example.com", jws.Issuer);
            Assert.Equal(now, jws.ExpirationTime);
            Assert.Null(jws.JwtId);
            Assert.Null(jws.IssuedAt);
            Assert.Null(jws.NotBefore);
            Assert.Null(jws.Subject);
            Assert.Null(jws.KeyId);
            Assert.Null(jws.Audience);
            Assert.Equal(SignatureAlgorithm.RsaSsaPssSha256, jws.Algorithm);
        }
コード例 #10
0
        public void EpochTime_ToUtcString_Returns_Correct_Value_From_DateTimeOffset_Constructor()
        {
            var expected  = new DateTimeOffset(2012, 12, 25, 23, 36, 45, TimeSpan.Zero);
            var epochTime = new EpochTime(expected);

            Assert.AreEqual("Tue, 25 Dec 2012 23:36:45 GMT", epochTime.ToUtcString());
        }
コード例 #11
0
        /// <summary>
        /// Get an access token from the issuer.
        /// </summary>
        /// <param name="issuer">The issuer.</param>
        /// <param name="scope">The scope to request.</param>
        /// <returns>The token response.</returns>
        public async Task <TokenResponse> GetAccessTokenAsync(string issuer, string scope)
        {
            // Use a signed JWT as client credentials.
            var payload = new JwtPayload();

            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Iss, _oidcModel.ClientId));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Sub, _oidcModel.ClientId));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Aud, _oidcModel.Audience));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Iat, EpochTime.GetIntDate(DateTime.UtcNow).ToString()));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Nbf, EpochTime.GetIntDate(DateTime.UtcNow.AddSeconds(-5)).ToString()));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Exp, EpochTime.GetIntDate(DateTime.UtcNow.AddMinutes(5)).ToString()));
            var bytes = CryptoRandom.CreateRandomKey(32);
            var jti   = Base64Url.Encode(bytes);

            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Jti, jti));

            var handler = new JwtSecurityTokenHandler();
            var rsaKey  = _rsaKeyService.GetKey();
            var jwt     = handler.WriteToken(new JwtSecurityToken(new JwtHeader(new SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha512)), payload));

            var httpClient = _httpClientFactory.CreateClient();

            return(await httpClient.RequestClientCredentialsTokenWithJwtAsync(
                       new JwtClientCredentialsTokenRequest
            {
                Address = _oidcModel.AccessTokenUrl,
                ClientId = _oidcModel.ClientId,
                Jwt = jwt,
                Scope = scope
            }));
        }
コード例 #12
0
        public async Task <TokenResponse> GetAccessTokenAsync(string clientId, string accessTokenEndpoint, string scope, string keyVaultKeyString)
        {
            TokenResponse errorResponse = ValidateParameters((nameof(clientId), clientId), (nameof(accessTokenEndpoint), accessTokenEndpoint), (nameof(scope), scope), (nameof(keyVaultKeyString), keyVaultKeyString));

            if (errorResponse != null)
            {
                return(errorResponse);
            }

            // Use a signed JWT as client credentials.
            var payload = new JwtPayload();

            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Iss, clientId));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Sub, clientId));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Aud, accessTokenEndpoint));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Iat, EpochTime.GetIntDate(DateTime.UtcNow).ToString(), ClaimValueTypes.Integer64));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Nbf, EpochTime.GetIntDate(DateTime.UtcNow.AddSeconds(-5)).ToString(), ClaimValueTypes.Integer64));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Exp, EpochTime.GetIntDate(DateTime.UtcNow.AddMinutes(5)).ToString(), ClaimValueTypes.Integer64));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Jti, CryptoRandom.CreateUniqueId()));

            var handler     = new JwtSecurityTokenHandler();
            var credentials = GetSigningCredentialsFromKeyVault(keyVaultKeyString);
            var jwt         = handler.WriteToken(new JwtSecurityToken(new JwtHeader(credentials), payload));

            var request = new JwtClientCredentialsTokenRequest {
                Address = accessTokenEndpoint, ClientId = clientId, Jwt = jwt, Scope = scope
            };

            return(await _httpClientFactory
                   .CreateClient(EdnaExternalHttpHandler.Name)
                   .RequestClientCredentialsTokenWithJwtAsync(request));
        }
コード例 #13
0
        public void EpochTime_ToString_Returns_Correct_Value_From_Seconds_Constructor()
        {
            const int expected  = 1356478605;
            var       epochTime = new EpochTime(expected);

            Assert.AreEqual(expected.ToString(CultureInfo.InvariantCulture), epochTime.ToString());
        }
コード例 #14
0
        private static string CreateJwt(ECDsa key, string keyId, string clientId, string teamId, int expAt = 5)
        {
            var signingCredentials = new SigningCredentials(
                new ECDsaSecurityKey(key), SecurityAlgorithms.EcdsaSha256);

            var now = DateTime.UtcNow;

            var claims = new List <Claim>
            {
                new Claim(ClaimConstants.Issuer, teamId),
                new Claim(ClaimConstants.IssuedAt, EpochTime.GetIntDate(now).ToString(), ClaimValueTypes.Integer64),
                new Claim(ClaimConstants.Expiration, EpochTime.GetIntDate(now.AddMinutes(5)).ToString(), ClaimValueTypes.Integer64),
                new Claim(ClaimConstants.Audience, "https://appleid.apple.com"),
                new Claim(ClaimConstants.Sub, clientId)
            };

            var tokenJWT = new JwtSecurityToken(
                issuer: teamId,
                claims: claims,
                expires: now.AddMinutes(expAt),
                signingCredentials: signingCredentials
                );

            tokenJWT.Header.Add(ClaimConstants.KeyID, keyId);
            JwtSecurityTokenHandler _tokenHandler = new JwtSecurityTokenHandler();

            return(_tokenHandler.WriteToken(tokenJWT));
        }
コード例 #15
0
    public void SetMin()
    {
        PartialRow row = GetPartialRowWithAllTypes();

        for (int i = 0; i < row.Schema.Columns.Count; i++)
        {
            row.SetMin(i);
        }

        Assert.False(row.GetBool("bool"));
        Assert.Equal(sbyte.MinValue, row.GetSByte("int8"));
        Assert.Equal(short.MinValue, row.GetInt16("int16"));
        Assert.Equal(int.MinValue, row.GetInt32("int32"));
        Assert.Equal(long.MinValue, row.GetInt64("int64"));
        Assert.Equal(long.MinValue, row.GetInt64("timestamp"));
        Assert.Equal(EpochTime.FromUnixTimeDays(EpochTime.MinDateValue), row.GetDateTime("date"));
        Assert.Equal(float.MinValue, row.GetFloat("float"));
        Assert.Equal(double.MinValue, row.GetDouble("double"));
        Assert.Equal("", row.GetString("string"));
        Assert.Equal("", row.GetString("varchar"));
        Assert.Equal(new byte[0], row.GetBinary("binary"));
        Assert.Equal(-99.999m, row.GetDecimal("decimal32"));
        Assert.Equal(-99.999m, row.GetDecimal("decimal64"));
        Assert.Equal(-99.999m, row.GetDecimal("decimal128"));
    }
コード例 #16
0
        public void Write()
        {
            var descriptor = new SecurityEventTokenDescriptor
            {
                Type      = "secevent+jwt",
                Algorithm = SignatureAlgorithm.None,
                Issuer    = "https://scim.example.com",
                IssuedAt  = EpochTime.ToDateTime(1458496404),
                JwtId     = "4d3559ec67504aaba65d40b0363faad8",
                Audiences = new List <string> {
                    "https://scim.example.com/Feeds/98d52461fa5bbc879593b7754", "https://scim.example.com/Feeds/5d7604516b1d08641d7676ee7"
                }
            };

            var @event = new ScimCreateEvent
            {
                Ref        = "https://scim.example.com/Users/44f6142df96bd6ab61e7521d9",
                Attributes = { "id", "name", "userName", "password", "emails" }
            };

            descriptor.AddEvent("urn:ietf:params:scim:event:create", @event);

            var writer = new JwtWriter();
            var jwt    = writer.WriteTokenString(descriptor);

#if !NETSTANDARD2_0
            Assert.Equal("eyJ0eXAiOiJzZWNldmVudCtqd3QiLCJhbGciOiJub25lIn0.eyJpc3MiOiJodHRwczovL3NjaW0uZXhhbXBsZS5jb20iLCJpYXQiOjE0NTg0OTY0MDQsImp0aSI6IjRkMzU1OWVjNjc1MDRhYWJhNjVkNDBiMDM2M2ZhYWQ4IiwiYXVkIjpbImh0dHBzOi8vc2NpbS5leGFtcGxlLmNvbS9GZWVkcy85OGQ1MjQ2MWZhNWJiYzg3OTU5M2I3NzU0IiwiaHR0cHM6Ly9zY2ltLmV4YW1wbGUuY29tL0ZlZWRzLzVkNzYwNDUxNmIxZDA4NjQxZDc2NzZlZTciXSwiZXZlbnRzIjp7InVybjppZXRmOnBhcmFtczpzY2ltOmV2ZW50OmNyZWF0ZSI6eyJyZWYiOiJodHRwczovL3NjaW0uZXhhbXBsZS5jb20vVXNlcnMvNDRmNjE0MmRmOTZiZDZhYjYxZTc1MjFkOSIsImF0dHJpYnV0ZSI6WyJpZCIsIm5hbWUiLCJ1c2VyTmFtZSIsInBhc3N3b3JkIiwiZW1haWxzIl19fX0.", jwt);
#else
            Assert.Equal("eyJ0eXAiOiJzZWNldmVudFx1MDAyQmp3dCIsImFsZyI6Im5vbmUifQ.eyJpc3MiOiJodHRwczovL3NjaW0uZXhhbXBsZS5jb20iLCJpYXQiOjE0NTg0OTY0MDQsImp0aSI6IjRkMzU1OWVjNjc1MDRhYWJhNjVkNDBiMDM2M2ZhYWQ4IiwiYXVkIjpbImh0dHBzOi8vc2NpbS5leGFtcGxlLmNvbS9GZWVkcy85OGQ1MjQ2MWZhNWJiYzg3OTU5M2I3NzU0IiwiaHR0cHM6Ly9zY2ltLmV4YW1wbGUuY29tL0ZlZWRzLzVkNzYwNDUxNmIxZDA4NjQxZDc2NzZlZTciXSwiZXZlbnRzIjp7InVybjppZXRmOnBhcmFtczpzY2ltOmV2ZW50OmNyZWF0ZSI6eyJyZWYiOiJodHRwczovL3NjaW0uZXhhbXBsZS5jb20vVXNlcnMvNDRmNjE0MmRmOTZiZDZhYjYxZTc1MjFkOSIsImF0dHJpYnV0ZSI6WyJpZCIsIm5hbWUiLCJ1c2VyTmFtZSIsInBhc3N3b3JkIiwiZW1haWxzIl19fX0.", jwt);
#endif
        }
コード例 #17
0
 public Pass(Coordinate Observer, EpochTime ContactStart, EpochTime ContactEnd, double maxElevation)
 {
     this.location       = Observer;
     this.startOfContact = ContactStart;
     this.endOfContact   = ContactEnd;
     this.maxElevation   = maxElevation;
 }
コード例 #18
0
        public void Build_Jws_AutomaticClaims()
        {
            var builder = new JwtDescriptorBuilder();

            var now = EpochTime.ToDateTime(EpochTime.UtcNow);

            builder
            .SignWith(RsaJwk.GenerateKey(2048, true, SignatureAlgorithm.RsaSsaPssSha256))
            .ExpiresAfter(10)
            .NotBefore(5)
            .WithAutomaticId()
            .WithAutomaticIssuedAt();

            var descriptor = builder.Build();

            Assert.IsType <JwsDescriptor>(descriptor);
            var jws = (JwsDescriptor)descriptor;

            Assert.NotNull(jws.ExpirationTime);
            Assert.InRange((jws.ExpirationTime - now).Value.TotalSeconds - 10, -2, 2);
            Assert.NotNull(jws.JwtId);
            Assert.NotNull(jws.IssuedAt);
            Assert.InRange((jws.IssuedAt - now).Value.TotalSeconds, -2, 2);
            Assert.NotNull(jws.NotBefore);
            Assert.InRange((jws.NotBefore - now).Value.TotalSeconds - 5, -2, 2);
            Assert.Null(jws.Subject);
            Assert.Null(jws.KeyId);
            Assert.Null(jws.Audience);
            Assert.Equal(SignatureAlgorithm.RsaSsaPssSha256, jws.Algorithm);
        }
コード例 #19
0
        public void Read()
        {
            var key = new RsaJwk
                      (
                n: "w7Zdfmece8iaB0kiTY8pCtiBtzbptJmP28nSWwtdjRu0f2GFpajvWE4VhfJAjEsOcwYzay7XGN0b-X84BfC8hmCTOj2b2eHT7NsZegFPKRUQzJ9wW8ipn_aDJWMGDuB1XyqT1E7DYqjUCEOD1b4FLpy_xPn6oV_TYOfQ9fZdbE5HGxJUzekuGcOKqOQ8M7wfYHhHHLxGpQVgL0apWuP2gDDOdTtpuld4D2LK1MZK99s9gaSjRHE8JDb1Z4IGhEcEyzkxswVdPndUWzfvWBBWXWxtSUvQGBRkuy1BHOa4sP6FKjWEeeF7gm7UMs2Nm2QUgNZw6xvEDGaLk4KASdIxRQ",
                e: "AQAB"
                      )
            {
                Kid = "1e9gdk7",
                Alg = SignatureAlgorithm.RsaSha256.Utf8Name
            };
            var reader = new JwtReader();

            var policy = new TokenValidationPolicyBuilder()
                         .RequireSignature(key)
                         .Build();

            var result = reader.TryReadToken("eyJraWQiOiIxZTlnZGs3IiwiYWxnIjoiUlMyNTYifQ.ewogImlzcyI6ICJodHRwOi8vc2VydmVyLmV4YW1wbGUuY29tIiwKICJzdWIiOiAiMjQ4Mjg5NzYxMDAxIiwKICJhdWQiOiAiczZCaGRSa3F0MyIsCiAibm9uY2UiOiAibi0wUzZfV3pBMk1qIiwKICJleHAiOiAxMzExMjgxOTcwLAogImlhdCI6IDEzMTEyODA5NzAsCiAibmFtZSI6ICJKYW5lIERvZSIsCiAiZ2l2ZW5fbmFtZSI6ICJKYW5lIiwKICJmYW1pbHlfbmFtZSI6ICJEb2UiLAogImdlbmRlciI6ICJmZW1hbGUiLAogImJpcnRoZGF0ZSI6ICIwMDAwLTEwLTMxIiwKICJlbWFpbCI6ICJqYW5lZG9lQGV4YW1wbGUuY29tIiwKICJwaWN0dXJlIjogImh0dHA6Ly9leGFtcGxlLmNvbS9qYW5lZG9lL21lLmpwZyIKfQ.rHQjEmBqn9Jre0OLykYNnspA10Qql2rvx4FsD00jwlB0Sym4NzpgvPKsDjn_wMkHxcp6CilPcoKrWHcipR2iAjzLvDNAReF97zoJqq880ZD1bwY82JDauCXELVR9O6_B0w3K-E7yM2macAAgNCUwtik6SjoSUZRcf-O5lygIyLENx882p6MtmwaL1hd6qn5RZOQ0TLrOYu0532g9Exxcm-ChymrB4xLykpDj3lUivJt63eEGGN6DH5K6o33TcxkIjNrCD4XB1CKKumZvCedgHHF3IAK4dVEDSUoGlH9z4pP_eWYNXvqQOjGs-rDaQzUHl6cQQWNiDpWOl_lxXjQEvQ", policy);
            var token  = result.Token.AsIdToken();

            Assert.Equal("http://server.example.com", token.Issuer);
            Assert.Equal("248289761001", token.Subject);
            Assert.Equal("s6BhdRkqt3", token.Audiences.FirstOrDefault());
            Assert.Equal("n-0S6_WzA2Mj", token.Nonce);
            Assert.Equal(EpochTime.ToDateTime(1311281970), token.ExpirationTime);
            Assert.Equal(EpochTime.ToDateTime(1311280970), token.IssuedAt);
            Assert.Equal("Jane Doe", token.Payload["name"]);
            Assert.Equal("Jane", token.GivenName);
            Assert.Equal("Doe", token.FamilyName);
            Assert.Equal("female", token.Gender);
            Assert.Equal("0000-10-31", token.Birthdate);
            Assert.Equal("*****@*****.**", token.Email);
            Assert.Equal("http://example.com/janedoe/me.jpg", token.Picture);
        }
コード例 #20
0
        /// <summary>
        /// Adds Nbf, Exp, Iat, Iss and Aud claims to payload
        /// </summary>
        /// <param name="issuer">If this value is not null, a { iss, 'issuer' } claim will be added, overwriting any 'iss' claim in <see cref="JwtPayload"/> instance.</param>
        /// <param name="audience">If this value is not null, a { aud, 'audience' } claim will be added, appending to any 'aud' claims in <see cref="JwtPayload"/> instance.</param>
        /// <param name="notBefore">If notbefore.HasValue a { nbf, 'value' } claim is added, overwriting any 'nbf' claim in <see cref="JwtPayload"/> instance.</param>
        /// <param name="expires">If expires.HasValue a { exp, 'value' } claim is added, overwriting any 'exp' claim in <see cref="JwtPayload"/> instance.</param>
        /// <param name="issuedAt">If issuedAt.HasValue is 'true' a { iat, 'value' } claim is added, overwriting any 'iat' claim in <see cref="JwtPayload"/> instance.</param>
        internal void AddFirstPriorityClaims(string issuer, string audience, DateTime?notBefore, DateTime?expires, DateTime?issuedAt)
        {
            if (expires.HasValue)
            {
                if (notBefore.HasValue)
                {
                    if (notBefore.Value >= expires.Value)
                    {
                        throw LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(LogMessages.IDX12401, LogHelper.MarkAsNonPII(expires.Value), LogHelper.MarkAsNonPII(notBefore.Value))));
                    }

                    this[JwtRegisteredClaimNames.Nbf] = EpochTime.GetIntDate(notBefore.Value.ToUniversalTime());
                }

                this[JwtRegisteredClaimNames.Exp] = EpochTime.GetIntDate(expires.Value.ToUniversalTime());
            }

            if (issuedAt.HasValue)
            {
                this[JwtRegisteredClaimNames.Iat] = EpochTime.GetIntDate(issuedAt.Value.ToUniversalTime());
            }

            if (!string.IsNullOrEmpty(issuer))
            {
                this[JwtRegisteredClaimNames.Iss] = issuer;
            }

            // if could be the case that some of the claims above had an 'aud' claim;
            if (!string.IsNullOrEmpty(audience))
            {
                AddClaim(new Claim(JwtRegisteredClaimNames.Aud, audience, ClaimValueTypes.String));
            }
        }
コード例 #21
0
        private string GenerateSignedRedeemUrl(string emailAddress, string nonce)
        {
            var now       = DateTime.UtcNow;
            var notBefore = EpochTime.GetIntDate(now);
            var expires   = EpochTime.GetIntDate(now.Add(ActivationTokenLifetime));

            using (var hashAlgorithm = new HMACSHA256(Encoding.UTF8.GetBytes(_options.ActivationKey)))
            {
                var signature = Convert.ToBase64String(
                    hashAlgorithm.ComputeHash(
                        Encoding.UTF8.GetBytes(GenerateRedeemUrl(
                                                   emailAddress,
                                                   nonce,
                                                   notBefore,
                                                   expires,
                                                   string.Empty))));

                return(GenerateRedeemUrl(
                           emailAddress,
                           nonce,
                           notBefore,
                           expires,
                           signature));
            }
        }
コード例 #22
0
ファイル: AuthController.cs プロジェクト: IvanYuriev/Xpence
        private string CreateAccessToken(string clientSub)
        {
            var secret             = Encoding.ASCII.GetBytes(_configuration["JwtConfig:Secret"]);
            var key                = new SymmetricSecurityKey(secret);
            var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //TODO: should be smth like: new SigningCredentials(new X509SecurityKey(cert), "RS256");
            var header = new JwtHeader(signingCredentials);

            var expirationDate          = DateTime.Now.AddMinutes(30); //TODO: put settings from config
            var expirationDateInSeconds = EpochTime.GetIntDate(expirationDate);
            var payload = new JwtPayload
            {
                {
                    JwtRegisteredClaimNames.Exp, expirationDateInSeconds.ToString()
                },
                {
                    JwtRegisteredClaimNames.Sub, clientSub
                },
                {
                    JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()
                },
                {
                    JwtRegisteredClaimNames.Iss, "Xpence"
                }
            };
            var token       = new JwtSecurityToken(header, payload);
            var tokenSigned = _handler.WriteToken(token);

            return(tokenSigned);
        }
コード例 #23
0
        public void EpochTime_ToDateTimeOffset_Returns_Correct_Value_From_DateTimeOffset_Constructor()
        {
            var expected  = new DateTimeOffset(2012, 12, 25, 23, 36, 45, TimeSpan.Zero);
            var epochTime = new EpochTime(expected);

            Assert.AreEqual(expected, epochTime.ToDateTimeOffset());
        }
コード例 #24
0
ファイル: Satellite.cs プロジェクト: GAnatoliy/holo-sky
        public GeoCoordinate GetGeodeticCoordinateNow()
        {
            var tleISS      = ParserTLE.parseTle(TleLine1, TleLine2, TleLine0);
            var currentTime = new EpochTime(DateTime.UtcNow);
            // TODO: use sdp4 for satellites with medium/high orbit.
            var data             = SatFunctions.getSatPositionAtTime(tleISS, currentTime, Sgp4.wgsConstant.WGS_84);
            var secondsFromStart = (currentTime.getEpoch() - Math.Truncate(currentTime.getEpoch())) * 24 * 60 * 60;
            var omega            = OMEGA_E * secondsFromStart;

            var C = MathNet.Numerics.LinearAlgebra.Double.DenseMatrix.OfArray(
                new double[, ] {
                { Math.Cos(omega), Math.Sin(omega), 0 },
                { -Math.Sin(omega), Math.Cos(omega), 0 },
                { 0, 0, 1 }
            });

            var p = MathNet.Numerics.LinearAlgebra.Double.DenseMatrix.OfArray(
                new double[, ] {
                { data.getX() * 1000 },
                { data.getY() * 1000 },
                { data.getZ() * 1000 }
            });

            var ecr = C * p;

            GpsUtils.EcefToGeodetic(ecr[0, 0], ecr[1, 0], ecr[2, 0], out var lat, out var lon, out var h);

            return(new GeoCoordinate(lat, lon, h));
        }
コード例 #25
0
    /// <summary>
    /// Utility method to return a random date value.
    /// </summary>
    public static DateTime RandomDate(Random random)
    {
        int bound = EpochTime.MaxDateValue - EpochTime.MinDateValue + 1;
        int days  = random.Next(bound) + EpochTime.MinDateValue;

        return(EpochTime.FromUnixTimeDays(days));
    }
コード例 #26
0
        /// <summary>
        /// Generates the signed JSON Web Token
        /// </summary>
        /// <param name="privateKey"></param>
        /// <param name="teamId"></param>
        /// <param name="clientId"></param>
        /// <param name="keyId"></param>
        /// <returns></returns>
        public string GenerateAppleClientSecret(string privateKey, string teamId, string clientId, string keyId)
        {
            var key      = GetFormattedPrivateKey(privateKey);
            var ecDsaCng = ECDsa.Create();

            ecDsaCng.ImportPkcs8PrivateKey(Convert.FromBase64String(key), out var _);

            var signingCredentials = new SigningCredentials(
                new ECDsaSecurityKey(ecDsaCng), SecurityAlgorithms.EcdsaSha256);

            var now = DateTime.UtcNow;

            var claims = new List <Claim>
            {
                new Claim(ClaimConstants.Issuer, teamId),
                new Claim(ClaimConstants.IssuedAt, EpochTime.GetIntDate(now).ToString(), ClaimValueTypes.Integer64),
                new Claim(ClaimConstants.Expiration, EpochTime.GetIntDate(now.AddMinutes(5)).ToString(), ClaimValueTypes.Integer64),
                new Claim(ClaimConstants.Audience, "https://appleid.apple.com"),
                new Claim(ClaimConstants.Sub, clientId)
            };

            var token = new JwtSecurityToken(
                issuer: teamId,
                claims: claims,
                expires: now.AddMinutes(5),
                signingCredentials: signingCredentials);

            token.Header.Add(ClaimConstants.KeyID, keyId);

            return(_tokenHandler.WriteToken(token));
        }
コード例 #27
0
        /// <summary>
        /// Build and send the deep linking response.
        /// </summary>
        /// <returns></returns>
        public async Task <IActionResult> OnPostAssignActivities()
        {
            var handler = new JwtSecurityTokenHandler();

            Token      = handler.ReadJwtToken(IdToken);
            LtiRequest = new LtiDeepLinkingRequest(Token.Payload);

            var response = new LtiDeepLinkingResponse
            {
                Data         = LtiRequest.DeepLinkingSettings.Data,
                DeploymentId = LtiRequest.DeploymentId
            };

            var contentItems     = new List <ContentItem>();
            var customParameters = LtiRequest.Custom;

            foreach (var activity in Activities)
            {
                if (activity.Selected)
                {
                    var contentItem = new LtiLinkItem
                    {
                        Title  = activity.Title,
                        Text   = activity.Description,
                        Url    = Url.Page("./Tool", null, null, Request.Scheme),
                        Custom = new Dictionary <string, string>
                        {
                            { "activity_id", activity.Id.ToString() }
                        }
                    };

                    if (customParameters != null)
                    {
                        foreach (var keyValue in LtiRequest.Custom)
                        {
                            contentItem.Custom.TryAdd(keyValue.Key, keyValue.Value);
                        }
                    }

                    contentItems.Add(contentItem);
                }
            }

            response.ContentItems = contentItems.ToArray();
            response.AddClaim(new Claim(JwtRegisteredClaimNames.Iss, LtiRequest.Aud[0]));
            response.AddClaim(new Claim(JwtRegisteredClaimNames.Aud, LtiRequest.Iss));
            response.AddClaim(new Claim(JwtRegisteredClaimNames.Sub, LtiRequest.Sub));
            response.AddClaim(new Claim(JwtRegisteredClaimNames.Iat, EpochTime.GetIntDate(DateTime.UtcNow).ToString()));
            response.AddClaim(new Claim(JwtRegisteredClaimNames.Nbf, EpochTime.GetIntDate(DateTime.UtcNow.AddSeconds(-5)).ToString()));
            response.AddClaim(new Claim(JwtRegisteredClaimNames.Exp, EpochTime.GetIntDate(DateTime.UtcNow.AddMinutes(5)).ToString()));
            response.AddClaim(new Claim(JwtRegisteredClaimNames.Nonce, IdentityModel.CryptoRandom.CreateRandomKeyString(8)));

            var platform = await _context.GetPlatformByIssuerAsync(LtiRequest.Iss);

            var credentials = PemHelper.SigningCredentialsFromPemString(platform.PrivateKey);
            var jwt         = handler.WriteToken(new JwtSecurityToken(new JwtHeader(credentials), response));

            return(Post("id_token", jwt, LtiRequest.DeepLinkingSettings.DeepLinkReturnUrl));
        }
コード例 #28
0
        public void EpochTime_TryParse_Fails_Given_Empty_String()
        {
            EpochTime epochTime;
            var       parsed = EpochTime.TryParseSeconds("", out epochTime);

            Assert.IsFalse(parsed);
            Assert.IsNull(epochTime);
        }
コード例 #29
0
        public void EpochTime_TryParse_Fails_Given_Text()
        {
            EpochTime epochTime;
            var       parsed = EpochTime.TryParseSeconds("Shiny", out epochTime);

            Assert.IsFalse(parsed);
            Assert.IsNull(epochTime);
        }
コード例 #30
0
        public void EpochTime_TryParse_Fails_Given_Decimal_Number_Of_Seconds()
        {
            EpochTime epochTime;
            var       parsed = EpochTime.TryParseSeconds("123.45", out epochTime);

            Assert.IsFalse(parsed);
            Assert.IsNull(epochTime);
        }