public async Task EncryptAndDecrypt_UsingBrainKeys() { Func <TokenContext, Task <string> > tokenCallback = (c) => { var virgilCrypto = new VirgilCrypto(); var signer = new VirgilAccessTokenSigner(); var apiKey = virgilCrypto.ImportPrivateKey( Bytes.FromString(AppSettings.Get.ApiKey, StringEncoding.BASE64)); var generator = new JwtGenerator(AppSettings.Get.AppId, apiKey, AppSettings.Get.ApiKeyId, TimeSpan.FromDays(1), signer); var jwt = generator.GenerateToken("BRAINKEY_CLIENT"); return(Task.FromResult(jwt.ToString())); }; var brainKey = BrainKey.Initialize(tokenCallback); var keyPair1 = await brainKey.GenerateKeyPair("some password"); await Task.Delay(TimeSpan.FromSeconds(2)); var keyPair2 = await brainKey.GenerateKeyPair("some password"); await Task.Delay(TimeSpan.FromSeconds(2)); var crypto = new VirgilCrypto(); var plaindata = GetRandom.Bytes(128); var chipherdata = crypto.SignThenEncrypt(plaindata, keyPair1.PrivateKey, keyPair2.PublicKey); var originaldata = crypto.DecryptThenVerify(chipherdata, keyPair2.PrivateKey, keyPair1.PublicKey); originaldata.Should().BeEquivalentTo(plaindata); }
public static Tuple <Jwt, JwtGenerator> PredefinedToken( this Faker faker, VirgilAccessTokenSigner signer, TimeSpan lifeTime, out string apiPublicKeyId, out string apiPublicKeyBase64) { var crypto = new VirgilCrypto(); var apiKeyPair = crypto.GenerateKeys(); var fingerprint = crypto.GenerateHash(crypto.ExportPublicKey(apiKeyPair.PublicKey)); apiPublicKeyId = Bytes.ToString(fingerprint, StringEncoding.HEX); apiPublicKeyBase64 = Bytes.ToString( crypto.ExportPublicKey(apiKeyPair.PublicKey), StringEncoding.BASE64); var jwtGenerator = new JwtGenerator( faker.AppId(), apiKeyPair.PrivateKey, apiPublicKeyId, lifeTime, signer); var additionalData = new Dictionary <string, string> { { "username", "some_username" } }; var dict = additionalData.ToDictionary(entry => (object)entry.Key, entry => (object)entry.Value); var token = jwtGenerator.GenerateToken("some_identity", dict); return(new Tuple <Jwt, JwtGenerator>(token, jwtGenerator)); }
public async Task AuthenticateAsync(string issuer, string audience, DateTime expiration, AuthorizationLevel expectedLevel) { using (var tempEnvironment = new TestScopedEnvironmentVariable("AzureWebEncryptionKey", TestKeyValue)) { // Create an expired test token var token = JwtGenerator.GenerateToken(issuer, audience, notBefore: DateTime.UtcNow.AddHours(-1), expires: expiration); var controllerContext = new HttpControllerContext() { Request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://localhost/admin/test")) }; controllerContext.Request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); var actionContext = new HttpActionContext() { ControllerContext = controllerContext }; var attribute = new JwtAuthenticationAttribute(); await attribute.AuthenticateAsync(new HttpAuthenticationContext(actionContext, null), CancellationToken.None); Assert.Equal(expectedLevel, controllerContext.Request.GetAuthorizationLevel()); } }
public static string GenerateFunctionToken() { string siteName = ServerConfiguration.GetApplicationName(); string issuer = $"https://{siteName}.scm.azurewebsites.net"; string audience = $"https://{siteName}.azurewebsites.net/azurefunctions"; return(JwtGenerator.GenerateToken(issuer, audience, expires: DateTime.UtcNow.AddMinutes(2))); }
public void IssuedToken_WithDefaultValidation_SucceedsValidation() { using (var variables = new TestScopedEnvironmentVariable(Constants.AzureWebsiteLocalEncryptionKey, TestKeyValue)) { var token = JwtGenerator.GenerateToken("testissuer", "testaudience"); bool result = JwtGenerator.IsTokenValid(token); Assert.True(result); } }
public static PythiaProtocol Initialize(PythiaProtocolConfig config) { if (config.ProofKeys == null || !config.ProofKeys.Any()) { throw new ArgumentException( $"{nameof(config.ProofKeys)} value cannot be null or empty"); } if (string.IsNullOrWhiteSpace(config.AppId)) { throw new ArgumentException( $"{nameof(config.AppId)} value cannot be null or empty"); } if (string.IsNullOrWhiteSpace(config.ApiKeyId)) { throw new ArgumentException( $"{nameof(config.ApiKeyId)} value cannot be null or empty"); } if (string.IsNullOrWhiteSpace(config.ApiKey)) { throw new ArgumentException( $"{nameof(config.ApiKey)} value cannot be null or empty"); } Func <TokenContext, Task <string> > tokenCallback = (c) => { var virgilCrypto = new VirgilCrypto(); var signer = new VirgilAccessTokenSigner(); var apiKey = virgilCrypto.ImportPrivateKey( Bytes.FromString(config.ApiKey, StringEncoding.BASE64)); var generator = new JwtGenerator(config.AppId, apiKey, config.ApiKeyId, TimeSpan.FromDays(1), signer); var jwt = generator.GenerateToken("PYTHIA_CLIENT"); return(Task.FromResult(jwt.ToString())); }; var connection = new ServiceConnection(config.ApiURL); var tokenProvider = new CachingJwtProvider(tokenCallback); var client = new PythiaClient(connection, new NewtonsoftJsonSerializer()); var pythiaCrypto = new PythiaCrypto(); var protocol = new PythiaProtocol(client, pythiaCrypto, tokenProvider, config.ProofKeys); return(protocol); }
private Jwt GenerateJwt(string identity, PrivateKey apiPrivateKey, string apiPublicKeyId) { var jwtGenerator = new JwtGenerator( AppSettings.AppId, apiPrivateKey, apiPublicKeyId, TimeSpan.FromMinutes(10), Substitute.For <VirgilAccessTokenSigner>()); var jwt = jwtGenerator.GenerateToken(identity); return(jwt); }
public async Task YTC16() { var correnctPassword = "******"; var wrongPassword = "******"; var crypto = Substitute.For <IPythiaCrypto>(); crypto.Blind(correnctPassword).Returns(new PythiaCrypto().Blind(correnctPassword)); crypto.Blind(wrongPassword).Returns(new PythiaCrypto().Blind(wrongPassword)); crypto.Deblind(Arg.Any <byte[]>(), Arg.Any <byte[]>()) .Returns((arg) => new PythiaCrypto().Deblind((byte[])arg[0], (byte[])arg[1])); crypto.GenerateSalt().Returns(new PythiaCrypto().GenerateSalt()); crypto.Verify(Arg.Any <PythiaProofParams>()).Returns(true, false, false, false, false); var virgilCrypto = new VirgilCrypto(); var signer = new VirgilAccessTokenSigner(); var apiKey = virgilCrypto.ImportPrivateKey(Bytes.FromString(AppSettings.Get.ApiKey, StringEncoding.BASE64)); var generator = new JwtGenerator(AppSettings.Get.AppId, apiKey, AppSettings.Get.ApiKeyId, TimeSpan.FromDays(1), signer); var jwt = generator.GenerateToken("PYTHIA-CLIENT"); var connection = new ServiceConnection(AppSettings.Get.ApiURL); var tokenProvider = new ConstAccessTokenProvider(jwt); var client = new PythiaClient(connection, new NewtonsoftJsonSerializer()); var protocol = new PythiaProtocol(client, crypto, tokenProvider, AppSettings.Get.ProofKeys.Skip(1)); var bpp = await protocol.CreateBreachProofPasswordAsync(correnctPassword); await Task.Delay(TimeSpan.FromSeconds(2)); var verifyResult1 = await protocol.VerifyBreachProofPasswordAsync(correnctPassword, bpp, false); verifyResult1.Should().BeTrue(); await Task.Delay(TimeSpan.FromSeconds(2)); Func <Task> verifyResult2 = async() => { await protocol.VerifyBreachProofPasswordAsync(correnctPassword, bpp, true); }; verifyResult2.Should().Throw <Exception>(); await Task.Delay(TimeSpan.FromSeconds(2)); var verifyResult3 = await protocol.VerifyBreachProofPasswordAsync(wrongPassword, bpp, false); verifyResult3.Should().BeFalse(); await Task.Delay(TimeSpan.FromSeconds(2)); Func <Task> verifyResult4 = async() => { await protocol.VerifyBreachProofPasswordAsync(wrongPassword, bpp, true); }; verifyResult4.Should().Throw <Exception>(); await Task.Delay(TimeSpan.FromSeconds(2)); }
public IActionResult Authenticate([FromBody] AuthenticateModel model) // Login { var user = _userService.GetUserByCredentials(model.Username, model.Password); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } var tokenHandler = new JwtSecurityTokenHandler(); user.Token = tokenHandler.WriteToken(JwtGenerator.GenerateToken(user, tokenHandler)); return(Ok(user)); }
public async Task <IActionResult> SecureLogin(LoginModel model) { var user = await _userManager.FindByNameAsync(model.Username); if (user != null && await _userManager.CheckPasswordAsync(user, model.Password)) { var role = await _userManager.GetRolesAsync(user); var crypto = new VirgilCrypto(); var appKey = crypto.ImportPrivateKey(Bytes.FromString(_appsettings.APPKEYBASE64, StringEncoding.BASE64), _appsettings.APP_KEY_PASSWORD.ToString()); var accessTokenSigner = new VirgilAccessTokenSigner(); var jwtGenerator = new JwtGenerator(_appsettings.APP_ID, appKey, _appsettings.APP_KEY_ID, TimeSpan.FromMinutes(5), accessTokenSigner); var token = jwtGenerator.GenerateToken(user.Id).ToString() + jwtGenerator.GenerateToken(user.UserName).ToString() + jwtGenerator.GenerateToken(role.FirstOrDefault()).ToString(); return(Ok(new { token, user.Id, user.UserName, user.Email })); } return(BadRequest(new { message = "Username or Password is Incorrect" })); }
public void IssuedToken_WithInvalidValues_FailsValidation() { using (var variables = new TestScopedEnvironmentVariable(Constants.AzureWebsiteLocalEncryptionKey, TestKeyValue)) { var token = JwtGenerator.GenerateToken("testissuer", "testaudience"); var testParameters = new TokenValidationParameters() { IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(TestKeyValue)), ValidateIssuer = true, ValidateAudience = true }; bool result = JwtGenerator.IsTokenValid(token, testParameters); Assert.False(result); } }
public void GeneratedToken_ContainsExpectedClaims() { using (var variables = new TestScopedEnvironmentVariable(Constants.AzureWebsiteLocalEncryptionKey, TestKeyValue)) { var issuer = "testissuer"; var audience = "testaudience"; var expiration = new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc); var notBefore = expiration.AddSeconds(-10); var token = JwtGenerator.GenerateToken(issuer, audience, notBefore, expiration); var jwt = new JwtSecurityToken(token); Assert.Equal(issuer, jwt.Issuer); Assert.Equal(audience, jwt.Audiences.First()); Assert.Equal(expiration, jwt.ValidTo); Assert.Equal(notBefore, jwt.ValidFrom); } }
public async Task <IActionResult> Login(LoginModel model) { var user = await _userManager.FindByNameAsync(model.Username); if (user != null && await _userManager.CheckPasswordAsync(user, model.Password)) { var role = await _userManager.GetRolesAsync(user); IdentityOptions _options = new IdentityOptions(); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim("UserID", user.Id.ToString()), new Claim("Username", user.UserName.ToString()), new Claim(_options.ClaimsIdentity.RoleClaimType, role.FirstOrDefault()) }), Expires = DateTime.UtcNow.AddMinutes(5), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appsettings.JWT_Secret)), SecurityAlgorithms.HmacSha256Signature) }; var tokenHandler = new JwtSecurityTokenHandler(); var securityToken = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.WriteToken(securityToken); var SecureRole = await _userManager.GetRolesAsync(user); var crypto = new VirgilCrypto(); var appKey = crypto.ImportPrivateKey(Bytes.FromString(_appsettings.APPKEYBASE64, StringEncoding.BASE64), _appsettings.APP_KEY_PASSWORD.ToString()); var accessTokenSigner = new VirgilAccessTokenSigner(); var jwtGenerator = new JwtGenerator(_appsettings.APP_ID, appKey, _appsettings.APP_KEY_ID, TimeSpan.FromMinutes(5), accessTokenSigner); var SecureToken = jwtGenerator.GenerateToken(user.Id).ToString() + jwtGenerator.GenerateToken(user.UserName).ToString() + jwtGenerator.GenerateToken(role.FirstOrDefault()).ToString(); return(Ok(new { token, SecureToken, user.Id, user.UserName, user.Email })); } else { return(BadRequest(new { message = "Username or Password is Incorrect" })); } }
public static Task <string> EmulateServerResponseToBuildTokenRequest(TokenContext tokenContext, double lifeTimeMin = 10) { var serverResponse = Task <string> .Factory.StartNew(() => { Thread.Sleep(1000); // simulation of long-term processing var data = new Dictionary <object, object> { { "username", "my_username" } }; var builder = new JwtGenerator( AppSettings.AppId, ApiPrivateKey(), AppSettings.ApiPublicKeyId, TimeSpan.FromMinutes(lifeTimeMin), new VirgilAccessTokenSigner() ); var identity = SomeHash(tokenContext.Identity); return(builder.GenerateToken(identity, data).ToString()); } ); return(serverResponse); }
public void CardManager_Should_RaiseExceptionIfGetsCardWithDifferentId() { // STC-34 var verifier = Substitute.For <ICardVerifier>(); verifier.VerifyCard(Arg.Any <Card>()).Returns(true); var crypto = new VirgilCrypto(); var keyPair = faker.PredefinedKeyPair(); var rawCardContent = new RawCardContent() { CreatedAt = DateTime.UtcNow, Identity = "test", PublicKey = crypto.ExportPublicKey(keyPair.PublicKey), Version = "5.0" }; var model = new RawSignedModel() { ContentSnapshot = SnapshotUtils.TakeSnapshot(rawCardContent) }; var signer = new ModelSigner(new VirgilCardCrypto()); signer.SelfSign( model, keyPair.PrivateKey, new Dictionary <string, string>() { { "info", "some_additional_info" } } ); var signCallBack = Substitute.For <Func <RawSignedModel, Task <RawSignedModel> > >(); signCallBack.Invoke(Arg.Any <RawSignedModel>()).Returns(args => (RawSignedModel)args[0]); var jwtGenerator = new JwtGenerator( AppSettings.AppId, IntegrationHelper.ApiPrivateKey(), AppSettings.ApiPublicKeyId, TimeSpan.FromMinutes(10), new VirgilAccessTokenSigner() ); var accessTokenProvider = Substitute.For <IAccessTokenProvider>(); var identity = faker.Random.AlphaNumeric(20); var token = jwtGenerator.GenerateToken(identity); accessTokenProvider.GetTokenAsync(Arg.Any <TokenContext>()).Returns( token ); var cardId = faker.CardId(); var client = Substitute.For <ICardClient>(); Func <Task <Tuple <RawSignedModel, bool> > > stub = async() => { return(new Tuple <RawSignedModel, bool>(model, false)); }; client.GetCardAsync(Arg.Any <string>(), Arg.Any <string>()).Returns(stub.Invoke()); var manager = new CardManager(new CardManagerParams() { CardCrypto = new VirgilCardCrypto(), AccessTokenProvider = accessTokenProvider, SignCallBack = signCallBack, Verifier = verifier, ApiUrl = AppSettings.CardsServiceAddress } ) { Client = client }; Assert.ThrowsAsync <CardVerificationException>(async() => await manager.GetCardAsync(cardId)); }
public async System.Threading.Tasks.Task Prepair_TestDataAsync() { var model = faker.PredefinedRawSignedModel(); var fullModel = faker.PredefinedRawSignedModel( "a666318071274adb738af3f67b8c7ec29d954de2cabfd71a942e6ea38e59fff9", true, true, true); var data = new Dictionary <string, string> { { "STC-1.as_string", model.ExportAsString() }, { "STC-1.as_json", model.ExportAsJson() }, { "STC-2.as_string", fullModel.ExportAsString() }, { "STC-2.as_json", fullModel.ExportAsJson() } }; var cardManager = faker.CardManager(); var card = cardManager.ImportCardFromString(model.ExportAsString()); var crypto = new VirgilCrypto(); data.Add("STC-3.as_string", cardManager.ExportCardAsString(card)); data.Add("STC-3.as_json", cardManager.ExportCardAsJson(card)); data.Add("STC-3.card_id", card.Id); data.Add("STC-3.public_key_base64", Bytes.ToString(crypto.ExportPublicKey(card.PublicKey), StringEncoding.BASE64)); fullModel = faker.PredefinedRawSignedModel(null, true, true, true); var fullCard = cardManager.ImportCardFromString(fullModel.ExportAsString()); data.Add("STC-4.as_string", cardManager.ExportCardAsString(fullCard)); data.Add("STC-4.as_json", cardManager.ExportCardAsJson(fullCard)); data.Add("STC-4.card_id", fullCard.Id); data.Add("STC-4.public_key_base64", Bytes.ToString(crypto.ExportPublicKey(fullCard.PublicKey), StringEncoding.BASE64)); foreach (var signature in fullCard.Signatures) { data.Add($"STC-4.signature_{signature.Signer}_base64", Bytes.ToString(signature.Signature, StringEncoding.BASE64)); } string apiPublicKeyId; string apiPublicKeyBase64; var(token, jwtGenerator) = faker.PredefinedToken( new VirgilAccessTokenSigner(), TimeSpan.FromMinutes(10), out apiPublicKeyId, out apiPublicKeyBase64); data.Add("STC-22.jwt", token.ToString()); data.Add("STC-22.api_public_key_base64", apiPublicKeyBase64); data.Add("STC-22.api_key_id", apiPublicKeyId); data.Add("STC-23.api_public_key_base64", apiPublicKeyBase64); data.Add("STC-23.api_key_id", apiPublicKeyId); data.Add("STC-23.app_id", jwtGenerator.AppId); data.Add("STC-23.api_private_key_base64", Bytes.ToString( crypto.ExportPrivateKey(jwtGenerator.ApiKey), StringEncoding.BASE64)); // STC-10 var cardKeyPair = crypto.GenerateKeys(); var cardIdentity = faker.Random.AlphaNumeric(10); var rawCardContent1 = new RawCardContent() { CreatedAt = DateTime.UtcNow, Identity = cardIdentity, PublicKey = crypto.ExportPublicKey(cardKeyPair.PublicKey), Version = "5.0", }; var rawSignedModel = new RawSignedModel() { ContentSnapshot = SnapshotUtils.TakeSnapshot(rawCardContent1) }; var signer = new ModelSigner(new VirgilCardCrypto()); signer.SelfSign(rawSignedModel, cardKeyPair.PrivateKey); var keyPair = crypto.GenerateKeys(); signer.Sign(rawSignedModel, new SignParams() { SignerPrivateKey = keyPair.PrivateKey, Signer = "extra" }); data.Add("STC-10.private_key1_base64", Bytes.ToString( crypto.ExportPrivateKey(keyPair.PrivateKey), StringEncoding.BASE64)); var accessTokenGenerator = new JwtGenerator( AppSettings.AppId, IntegrationHelper.ApiPrivateKey(), AppSettings.ApiPublicKeyId, TimeSpan.FromMinutes(10), new VirgilAccessTokenSigner() ); var accessTokenProvider = Substitute.For <IAccessTokenProvider>(); accessTokenProvider.GetTokenAsync(Arg.Any <TokenContext>()).Returns( accessTokenGenerator.GenerateToken(cardIdentity) ); var validator = new VirgilCardVerifier(new VirgilCardCrypto()) { VerifySelfSignature = true, VerifyVirgilSignature = true }; validator.ChangeServiceCreds(AppSettings.ServicePublicKeyDerBase64); var manager = new CardManager(new CardManagerParams() { CardCrypto = new VirgilCardCrypto(), AccessTokenProvider = accessTokenProvider, ApiUrl = AppSettings.CardsServiceAddress, Verifier = validator }); card = await manager.PublishCardAsync(rawSignedModel); data.Add("STC-10.as_string", manager.ExportCardAsString(card)); // STC - 11 rawSignedModel = faker.PredefinedRawSignedModel(null, false, false, false); data.Add("STC-11.as_string", rawSignedModel.ExportAsString()); // STC - 12 rawSignedModel = faker.PredefinedRawSignedModel(null, true, false, false); data.Add("STC-12.as_string", rawSignedModel.ExportAsString()); // STC - 14 rawSignedModel = faker.PredefinedRawSignedModel(null, false, true, false); data.Add("STC-14.as_string", rawSignedModel.ExportAsString()); // STC - 15 rawSignedModel = faker.PredefinedRawSignedModel(null, false, false, false); keyPair = crypto.GenerateKeys(); signer.Sign(rawSignedModel, new SignParams() { SignerPrivateKey = keyPair.PrivateKey, Signer = "self" }); data.Add("STC-15.as_string", rawSignedModel.ExportAsString()); // STC - 16 rawSignedModel = faker.PredefinedRawSignedModel(null, true, true, false); keyPair = crypto.GenerateKeys(); signer.Sign(rawSignedModel, new SignParams() { SignerPrivateKey = keyPair.PrivateKey, Signer = "extra" }); data.Add("STC-16.as_string", rawSignedModel.ExportAsString()); data.Add("STC-16.public_key1_base64", Bytes.ToString( crypto.ExportPublicKey(keyPair.PublicKey), StringEncoding.BASE64)); // STC - 28 (token, jwtGenerator) = faker.PredefinedToken( new VirgilAccessTokenSigner(), TimeSpan.FromMinutes(2), out apiPublicKeyId, out apiPublicKeyBase64); data.Add("STC-28.jwt", token.ToString()); data.Add("STC-28.jwt_identity", token.BodyContent.Identity); data.Add("STC-28.jwt_app_id", token.BodyContent.AppId); data.Add("STC-28.jw_issuer", token.BodyContent.Issuer); data.Add("STC-28.jwt_subject", token.BodyContent.Subject); data.Add("STC-28.jwt_additional_data", Configuration.Serializer.Serialize(token.BodyContent.AdditionalData)); data.Add("STC-28.jwt_expires_at", Configuration.Serializer.Serialize(token.BodyContent.ExpiresAt)); data.Add("STC-28.jwt_issued_at", Configuration.Serializer.Serialize(token.BodyContent.IssuedAt)); data.Add("STC-28.jwt_algorithm", token.HeaderContent.Algorithm); data.Add("STC-28.jwt_api_key_id", token.HeaderContent.KeyId); data.Add("STC-28.jwt_content_type", token.HeaderContent.ContentType); data.Add("STC-28.jwt_type", token.HeaderContent.Type); data.Add("STC-28.jwt_signature_base64", Bytes.ToString(token.SignatureData, StringEncoding.BASE64)); // STC - 29 (token, jwtGenerator) = faker.PredefinedToken( new VirgilAccessTokenSigner(), TimeSpan.FromDays(365), out apiPublicKeyId, out apiPublicKeyBase64); data.Add("STC-29.jwt", token.ToString()); data.Add("STC-29.jwt_identity", token.BodyContent.Identity); data.Add("STC-29.jwt_app_id", token.BodyContent.AppId); data.Add("STC-29.jw_issuer", token.BodyContent.Issuer); data.Add("STC-29.jwt_subject", token.BodyContent.Subject); data.Add("STC-29.jwt_additional_data", Configuration.Serializer.Serialize(token.BodyContent.AdditionalData)); data.Add("STC-29.jwt_expires_at", Configuration.Serializer.Serialize(token.BodyContent.ExpiresAt)); data.Add("STC-29.jwt_issued_at", Configuration.Serializer.Serialize(token.BodyContent.IssuedAt)); data.Add("STC-29.jwt_algorithm", token.HeaderContent.Algorithm); data.Add("STC-29.jwt_api_key_id", token.HeaderContent.KeyId); data.Add("STC-29.jwt_content_type", token.HeaderContent.ContentType); data.Add("STC-29.jwt_type", token.HeaderContent.Type); data.Add("STC-29.jwt_signature_base64", Bytes.ToString(token.SignatureData, StringEncoding.BASE64)); // STC - 34 keyPair = crypto.GenerateKeys(); var rawCardContent = new RawCardContent() { CreatedAt = DateTime.UtcNow, Identity = "test", PublicKey = crypto.ExportPublicKey(keyPair.PublicKey), Version = "5.0" }; model = new RawSignedModel() { ContentSnapshot = SnapshotUtils.TakeSnapshot(rawCardContent) }; signer.SelfSign( model, keyPair.PrivateKey, new Dictionary <string, string>() { { "info", "some_additional_info" } } ); data.Add("STC-34.private_key_base64", Bytes.ToString( crypto.ExportPrivateKey(keyPair.PrivateKey), StringEncoding.BASE64)); data.Add("STC-34.public_key_base64", Bytes.ToString( crypto.ExportPublicKey(keyPair.PublicKey), StringEncoding.BASE64)); data.Add("STC-34.self_signature_snapshot_base64", Bytes.ToString(model.Signatures.First().Snapshot, StringEncoding.BASE64)); data.Add("STC-34.content_snapshot_base64", Bytes.ToString( SnapshotUtils.TakeSnapshot(rawCardContent), StringEncoding.BASE64)); data.Add("STC-34.as_string", model.ExportAsString()); System.IO.File.WriteAllText(AppSettings.OutputTestDataPath, Configuration.Serializer.Serialize(data)); }
public static Jwt GenerateVirgilToken(string identity) { return(_jwtGenerator.GenerateToken(identity)); }
public async Task CardManager_Should_SendSecondRequestToCliet_IfTokenExpiredAndRetryOnUnauthorizedAsync() { // STC-26 var expiredJwtGenerator = new JwtGenerator( AppSettings.AppId, IntegrationHelper.ApiPrivateKey(), AppSettings.ApiPublicKeyId, TimeSpan.FromSeconds(1), Substitute.For <VirgilAccessTokenSigner>()); var jwtGenerator = new JwtGenerator( AppSettings.AppId, IntegrationHelper.ApiPrivateKey(), AppSettings.ApiPublicKeyId, TimeSpan.FromMinutes(5), new VirgilAccessTokenSigner() ); var identity = faker.Random.AlphaNumeric(20); var expiredToken = expiredJwtGenerator.GenerateToken(identity); var accessTokenProvider = Substitute.For <IAccessTokenProvider>(); // suppose we have got expired token at the first attempt // and we have got valid token at the second attempt accessTokenProvider.GetTokenAsync(Arg.Any <TokenContext>() ).Returns( args => ((TokenContext)args[0]).ForceReload ? jwtGenerator.GenerateToken(identity) : expiredToken ); var validator = new VirgilCardVerifier(new VirgilCardCrypto()) { VerifySelfSignature = true, VerifyVirgilSignature = true }; validator.ChangeServiceCreds(AppSettings.ServicePublicKeyDerBase64); var manager = new CardManager(new CardManagerParams() { CardCrypto = new VirgilCardCrypto(), AccessTokenProvider = accessTokenProvider, ApiUrl = AppSettings.CardsServiceAddress, RetryOnUnauthorized = true, Verifier = validator }); var keypair = new VirgilCrypto().GenerateKeys(); var card = await manager.PublishCardAsync( new CardParams() { Identity = identity, PublicKey = keypair.PublicKey, PrivateKey = keypair.PrivateKey }); Assert.NotNull(card); var searchCard = await manager.SearchCardsAsync(identity); Assert.AreEqual(searchCard.Count, 1); var getCard = await manager.GetCardAsync(card.Id); Assert.NotNull(getCard); }
public void CardManager_Should_RaiseExceptionIfGetsInvalidCard() { // STC-13 var verifier = Substitute.For <ICardVerifier>(); verifier.VerifyCard(Arg.Any <Card>()).Returns(false); var signCallBack = Substitute.For <Func <RawSignedModel, Task <RawSignedModel> > >(); signCallBack.Invoke(Arg.Any <RawSignedModel>()).Returns(args => (RawSignedModel)args[0]); var jwtGenerator = new JwtGenerator( faker.AppId(), IntegrationHelper.ApiPrivateKey(), AppSettings.ApiPublicKeyId, TimeSpan.FromMinutes(10), new VirgilAccessTokenSigner() ); var accessTokenProvider = Substitute.For <IAccessTokenProvider>(); var identity = faker.Random.AlphaNumeric(20); var token = jwtGenerator.GenerateToken(identity); accessTokenProvider.GetTokenAsync(Arg.Any <TokenContext>()).Returns( token ); var model = faker.PredefinedRawSignedModel(null, true, true, true); var client = Substitute.For <ICardClient>(); Func <Task <Tuple <RawSignedModel, bool> > > getStub = async() => { return(new Tuple <RawSignedModel, bool>(model, false)); }; Func <Task <RawSignedModel> > publishStub = async() => { return(model); }; Func <Task <IEnumerable <RawSignedModel> > > searchStub = async() => { return(new List <RawSignedModel>() { model }); }; client.GetCardAsync(Arg.Any <string>(), Arg.Any <string>()).Returns(getStub.Invoke()); client.PublishCardAsync(Arg.Any <RawSignedModel>(), Arg.Any <string>()).Returns(publishStub.Invoke()); client.SearchCardsAsync(Arg.Any <string>(), Arg.Any <string>()).Returns(searchStub.Invoke()); var cardId = faker.CardId(); var searchCardIdentity = faker.Random.AlphaNumeric(20); var manager = new CardManager(new CardManagerParams() { CardCrypto = new VirgilCardCrypto(), AccessTokenProvider = accessTokenProvider, SignCallBack = signCallBack, Verifier = verifier, ApiUrl = AppSettings.CardsServiceAddress } ) { Client = client }; Assert.Throws <CardVerificationException>(() => manager.ImportCardFromJson(model.ExportAsJson())); Assert.Throws <CardVerificationException>(() => manager.ImportCardFromString(model.ExportAsString())); Assert.ThrowsAsync <CardVerificationException>(async() => await manager.GetCardAsync(cardId)); Assert.ThrowsAsync <CardVerificationException>(async() => await manager.PublishCardAsync(model)); Assert.ThrowsAsync <CardVerificationException>(async() => await manager.SearchCardsAsync(searchCardIdentity)); Assert.Throws <CardVerificationException>(() => manager.ImportCard(model)); }