private static void CreateMostBasicTokenSnippet() { // using GuylianGilsing.JWT.Tokens; // using GuylianGilsing.JWT.Hashing; // using GuylianGilsing.JWT.Hashing.Algorithms; // Create a new token Token token = new Token(); // Register payload claims token.payload.RegisterClaim("iss", "https://example.com"); token.payload.RegisterClaim("sub", "code_snippet"); token.payload.RegisterClaim("aud", "github"); // Set the hashing algorithm token.hashAlgo = new Sha256Algo(); // Set the secret key token.secretKey = new Key("MySuperSecretKey"); // Sign the token TokenSigner signer = new TokenSigner(); string signedToken = signer.Sign(token); // Sign the token with a seperate key string otherSignedToken = signer.Sign(token, new Key("OtherKey")); }
public static void Main(String[] args) { TokenSigner tokenSigner = new TokenSigner(); if (args == null || args.Length == 0) { tokenSigner.ListCertificates(); Console.WriteLine("Help."); Console.WriteLine("First argument is the folder path."); Console.WriteLine("Second argument is the token pin."); } else { if (args.Length == 2) tokenSigner.TokenPin = args[1]; if (File.Exists(args[0] + @"\SourceDocumentJson.json") == false) { Console.WriteLine("The file " + args[0] + @"\SourceDocumentJson.json is not exist"); } else { String cades = ""; String SourceDocumentJson = File.ReadAllText(args[0] + @"\SourceDocumentJson.json"); JObject request = JsonConvert.DeserializeObject<JObject>(SourceDocumentJson, new JsonSerializerSettings() { FloatFormatHandling = FloatFormatHandling.String, FloatParseHandling = FloatParseHandling.Decimal, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateParseHandling = DateParseHandling.None }); //Start serialize String canonicalString = tokenSigner.Serialize(request); File.WriteAllBytes(args[0] + @"\CanonicalString.txt", System.Text.Encoding.UTF8.GetBytes(canonicalString)); // retrieve cades if (request["documentTypeVersion"].Value<string>() == "0.9") { cades = "ANY"; } else { cades = tokenSigner.SignWithCMS(canonicalString); } File.WriteAllBytes(args[0] + @"\Cades.txt", System.Text.Encoding.UTF8.GetBytes(cades)); JObject signaturesObject = new JObject( new JProperty("signatureType", "I"), new JProperty("value", cades)); JArray signaturesArray = new JArray(); signaturesArray.Add(signaturesObject); request.Add("signatures", signaturesArray); String fullSignedDocument = "{\"documents\":[" + request.ToString() + "]}"; File.WriteAllBytes(args[0] + @"\FullSignedDocument.json", System.Text.Encoding.UTF8.GetBytes(fullSignedDocument)); } } }
/// <summary> /// Creates an IAccessTokenProvider with the supplied test credentials. /// </summary> /// <param name="httpClient">The httpClient that makes the request to the auth server</param> /// <param name="tokenProvisioningEndpoint">The auth server</param> /// <param name="keyId">The id of the security token</param> /// <param name="rsaParameters">The public and private key for the supplied key id</param> /// <returns>An IAccessTokenProvider with the supplied test credentials</returns> public static IAccessTokenProvider Create(HttpClient httpClient, String tokenProvisioningEndpoint, Guid keyId, RSAParameters rsaParameters) { #pragma warning disable 618 IPrivateKeyProvider privateKeyProvider = new StaticPrivateKeyProvider(keyId, rsaParameters); #pragma warning restore 618 ITokenSigner tokenSigner = new TokenSigner(privateKeyProvider); IAuthServiceClient authServiceClient = new AuthServiceClient(httpClient, new Uri(tokenProvisioningEndpoint)); INonCachingAccessTokenProvider noCacheTokenProvider = new AccessTokenProvider(tokenSigner, authServiceClient); return(new CachedAccessTokenProvider(noCacheTokenProvider, Timeout.InfiniteTimeSpan)); }
public void DirectoryAllowed() { var url = TokenSigner.SignUrl(t => { t.Url = "https://token-tester.b-cdn.net/abc/"; t.SecurityKey = "SecurityKey"; t.ExpiresAt = new DateTimeOffset(2020, 08, 21, 15, 43, 07, TimeSpan.Zero); t.IsDirectory = true; }); url.ShouldBe <string>("https://token-tester.b-cdn.net/bcdn_token=e0fYj-NC_YeROS_0gTGvscP7HR_Du78I7WBVSDV8P4E&expires=1598024587/abc/"); }
public void WithPathAllowed() { var url = TokenSigner.SignUrl(t => { t.Url = "https://token-tester.b-cdn.net/abc/300kb.jpg"; t.SecurityKey = "SecurityKey"; t.ExpiresAt = new DateTimeOffset(2020, 08, 21, 15, 43, 07, TimeSpan.Zero); t.TokenPath = "/abc"; }); url.ShouldBe <string>("https://token-tester.b-cdn.net/abc/300kb.jpg?token=xwPaUzEMSgOZ7yl86K55G7len9n1UMiuP36IAyw8Mjs&token_path=%2Fabc&expires=1598024587"); }
public void WithIPAddressAllowed() { var url = TokenSigner.SignUrl(t => { t.Url = "https://token-tester.b-cdn.net/300kb.jpg"; t.SecurityKey = "SecurityKey"; t.ExpiresAt = new DateTimeOffset(2020, 08, 21, 15, 43, 07, TimeSpan.Zero); t.UserIp = "1.2.3.4"; }); url.ShouldBe <string>("https://token-tester.b-cdn.net/300kb.jpg?token=xUWMwsZcXfzxMvTTFiKAN6if1WBhDZV1Shjt_GOrjG0&expires=1598024587"); }
public void WithCountriesDisallowed() { var url = TokenSigner.SignUrl(t => { t.Url = "https://token-tester.b-cdn.net/300kb.jpg"; t.SecurityKey = "SecurityKey"; t.CountriesBlocked = new List <string> { "CA" }; t.ExpiresAt = new DateTimeOffset(2020, 08, 21, 15, 43, 07, TimeSpan.Zero); }); url.ShouldBe <string>("https://token-tester.b-cdn.net/300kb.jpg?token=bq6dlNKcoVbTrzCJepE5gHoC436eTtz97Ruk89V8tmU&token_countries_blocked=CA&expires=1598024587"); }
public void WithCountriesAllowed() { var url = TokenSigner.SignUrl(t => { t.Url = "https://token-tester.b-cdn.net/300kb.jpg"; t.SecurityKey = "SecurityKey"; t.CountriesAllowed = new List <string> { "CA" }; t.ExpiresAt = new DateTimeOffset(2020, 08, 21, 15, 43, 07, TimeSpan.Zero); t.TokenPath = "/"; }); url.ShouldBe <string>("https://token-tester.b-cdn.net/300kb.jpg?token=3ZdIIg1-PB_UOF62lQIqfT4MWr2ENIdd0KWnQVuej3w&token_countries=CA&token_path=%2F&expires=1598024587"); }
public void WithIPAddressAllowed_ConvienenceMethod() { var utcNowPlusOneHour = DateTimeOffset.UtcNow.Add(TimeSpan.FromHours(1)); var url = TokenSigner.SignUrl(t => { t.Url = "https://token-tester.b-cdn.net/300kb.jpg"; t.SecurityKey = "SecurityKey"; t.ExpiresAt = utcNowPlusOneHour; t.UserIp = "1.2.3.4"; }); var urlConvienent = TokenSigner.SignUrl("SecurityKey", "https://token-tester.b-cdn.net/300kb.jpg", utcNowPlusOneHour, "1.2.3.4"); urlConvienent.ShouldBe <string>(url); }
/// <summary> /// Creates an <see cref="ITokenSigner"/> instance which saves public keys to the provided <see cref="IPublicKeyDataProvider"/> /// </summary> /// <param name="publicKeyDataProvider">The <see cref="IPublicKeyDataProvider"/> for the local service</param> /// <param name="keyLifetime">The max time a private key and its tokens may be used for</param> /// <param name="keyRotationPeriod">How often to switch to signing with a new private key. The difference between this and <paramref name="keyLifetime"/> is the maximum token lifetime.</param> /// <returns>A new <see cref="ITokenSigner"/></returns> public static ITokenSigner Create( IPublicKeyDataProvider publicKeyDataProvider, TimeSpan keyLifetime, TimeSpan keyRotationPeriod ) { IPrivateKeyProvider privateKeyProvider = RsaPrivateKeyProvider .Factory .Create( publicKeyDataProvider, keyLifetime, keyRotationPeriod ); var tokenSigner = new TokenSigner(privateKeyProvider); return(tokenSigner); }
/// <summary> /// Creates an <see cref="ITokenSigner"/> instance which saves public keys to the provided <see cref="IPublicKeyDataProvider"/> /// </summary> /// <param name="publicKeyDataProvider">The <see cref="IPublicKeyDataProvider"/> for the local service</param> /// <param name="curve">The curve to use</param> /// <param name="keyLifetime">The max time a private key and its tokens may be used for</param> /// <param name="keyRotationPeriod">How often to switch to signing with a new private key. The difference between this and <paramref name="keyLifetime"/> is the maximum token lifetime.</param> /// <returns>A new <see cref="ITokenSigner"/></returns> public static ITokenSigner Create( IPublicKeyDataProvider publicKeyDataProvider, Curve curve, TimeSpan keyLifetime, TimeSpan keyRotationPeriod ) { CngAlgorithm algorithm; switch (curve) { case Curve.P521: { algorithm = CngAlgorithm.ECDsaP521; break; } case Curve.P384: { algorithm = CngAlgorithm.ECDsaP384; break; } case Curve.P256: default: { algorithm = CngAlgorithm.ECDsaP256; break; } } IPrivateKeyProvider privateKeyProvider = EcDsaPrivateKeyProvider .Factory .Create( publicKeyDataProvider, keyLifetime, keyRotationPeriod, algorithm ); var tokenSigner = new TokenSigner(privateKeyProvider); return(tokenSigner); }
/// <summary> /// Creates an <see cref="ITokenSigner"/> instance which saves public keys to the provided <see cref="IPublicKeyDataProvider"/> /// </summary> /// <param name="publicKeyDataProvider">The <see cref="IPublicKeyDataProvider"/> for the local service</param> /// <param name="curve">The curve to use</param> /// <param name="keyLifetime">The max time a private key and its tokens may be used for</param> /// <param name="keyRotationPeriod">How often to switch to signing with a new private key. The difference between this and <paramref name="keyLifetime"/> is the maximum token lifetime.</param> /// <returns>A new <see cref="ITokenSigner"/></returns> public static ITokenSigner Create( IPublicKeyDataProvider publicKeyDataProvider, Curve curve, TimeSpan keyLifetime, TimeSpan keyRotationPeriod ) { ECCurve curveInternal; switch (curve) { case Curve.P521: { curveInternal = ECCurve.NamedCurves.nistP256; break; } case Curve.P384: { curveInternal = ECCurve.NamedCurves.nistP384; break; } case Curve.P256: default: { curveInternal = ECCurve.NamedCurves.nistP521; break; } } IPrivateKeyProvider privateKeyProvider = EcDsaPrivateKeyProvider .Factory .Create( publicKeyDataProvider, keyLifetime, keyRotationPeriod, curveInternal ); var tokenSigner = new TokenSigner(privateKeyProvider); return(tokenSigner); }
static void Main(string[] args) { // Create a new token Token token = new Token(); // Register payload claims token.payload.RegisterClaim("iss", "https://example.com"); // Set the hashing algorithm token.hashAlgo = new Sha256Algo(); // Set the secret key token.secretKey = new Key("MyKey"); // Sign the token TokenSigner signer = new TokenSigner(); string signedToken = signer.Sign(token); Console.WriteLine(signedToken); Console.ReadLine(); }
public void init() { // Configuration can be taken from app. settings, but also configured as properties. // Shared Secret string s = ConfigurationManager.AppSettings["oauth2SharedSecret"]; if (s != null) { sharedSecret = s; } // Optional string ha = ConfigurationManager.AppSettings["oauth2HMACAlgorithm"]; if (ha != null) { hmacAlgorithm = ha; } // Build necessary components HMACTokenSigner ts = new HMACTokenSigner(); ts.Key = SharedSecret; if (HmacAlgorithm != null) { ts.SignAlg = HmacAlgorithm; } AESTokenEncrypter te = new AESTokenEncrypter(); te.Key = SharedSecret; tokenSigner = ts; tokenEncrypter = te; }
public AuditedTokenSignService(MilvanethDbContext context, ITimeService time, IConfigurationRoot root) { _context = context; _time = time; _signer = new TokenSigner(GetTokenKey(root)); }