コード例 #1
0
        public void ApiUriDefaultIsUsedForNullOrEmpty(string envVar)
        {
            Environment.SetEnvironmentVariable("YOTI_API_URL", envVar);
            YotiClient client = CreateYotiClient();

            Assert.AreEqual(_expectedDefaultUri, client.ApiUri);
        }
コード例 #2
0
ファイル: AccountController.cs プロジェクト: KiranBali/.net
        // GET: Account/Connect?token
        public ActionResult Connect(string token)
        {
            try
            {
                string sdkId            = ConfigurationManager.AppSettings["Yoti.SdkId"];
                var    privateKeyStream = System.IO.File.OpenText(Server.MapPath("~/application-key.pem"));
                var    yotiClient       = new YotiClient(sdkId, privateKeyStream);

                var activityDetails = yotiClient.GetActivityDetails(token);
                if (activityDetails.Outcome == ActivityOutcome.Success)
                {
                    var yotiProfile = activityDetails.UserProfile;

                    User user = UserManager.GetUserByYotiId(yotiProfile.Id);

                    // create new user if none exists
                    if (user == null)
                    {
                        user = new User
                        {
                            YotiId = yotiProfile.Id
                        };
                    }

                    // update user information
                    if (yotiProfile.Selfie != null)
                    {
                        user.Photo = yotiProfile.Selfie.Data;
                    }

                    if (!string.IsNullOrEmpty(yotiProfile.MobileNumber))
                    {
                        user.PhoneNumber = yotiProfile.MobileNumber;
                    }

                    UserManager.SaveUser(user);

                    var identity = new ClaimsIdentity(new[] {
                        new Claim(ClaimTypes.Name, user.Id.ToString()),
                    },
                                                      "ApplicationCookie");

                    var ctx         = Request.GetOwinContext();
                    var authManager = ctx.Authentication;

                    authManager.SignIn(identity);

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    return(RedirectToAction("LoginFailure"));
                }
            } catch (Exception e)
            {
                ViewBag.Error = e.ToString();
                return(View());
            }
        }
コード例 #3
0
        public void ApiUriSetForPrivateKeyInitialisationHttpClient()
        {
            AsymmetricCipherKeyPair keyPair = KeyPair.Get();

            YotiClient yotiClient = new YotiClient(new HttpClient(), _someSdkId, keyPair);

            Assert.AreEqual(_expectedDefaultUri, yotiClient.ApiUri);
        }
コード例 #4
0
        public async Task YotiClient_GetActivityDetailsAsync()
        {
            YotiClient client = CreateYotiClient();

            ActivityDetails activityDetails = await client.GetActivityDetailsAsync(encryptedToken);

            Assert.IsNotNull(activityDetails.Outcome);
        }
コード例 #5
0
        public void YotiClient_GetActivityDetails()
        {
            YotiClient client = CreateYotiClient();

            ActivityDetails activityDetails = client.GetActivityDetails(encryptedToken);

            Assert.IsNotNull(activityDetails.Outcome);
        }
コード例 #6
0
        public void ApiUriSetForStreamInitialisationHttpClient()
        {
            StreamReader privateStreamKey = KeyPair.GetValidKeyStream();

            YotiClient yotiClient = new YotiClient(new HttpClient(), _someSdkId, privateStreamKey);

            Assert.AreEqual(_expectedDefaultUri, yotiClient.ApiUri);
        }
コード例 #7
0
        public void ApiUriEnvVariableIsUsed()
        {
            Environment.SetEnvironmentVariable("YOTI_API_URL", "https://envapiuri.com");
            YotiClient client = CreateYotiClient();

            Uri expectedApiUri = new Uri("https://envapiuri.com");

            Assert.AreEqual(expectedApiUri, client.ApiUri);
        }
コード例 #8
0
        public void YotiClient_InvalidKeyStream_ThrowsException()
        {
            StreamReader keystream = GetInvalidFormatKeyStream();
            string       sdkId     = "fake-sdk-id";

            Assert.ThrowsException <ArgumentException>(() =>
            {
                YotiClient client = new YotiClient(sdkId, keystream);
            });
        }
コード例 #9
0
        public void YotiClient_EmptyAppId_ThrowsException()
        {
            StreamReader keystream = GetValidKeyStream();
            string       sdkId     = string.Empty;

            Assert.ThrowsException <ArgumentNullException>(() =>
            {
                YotiClient client = new YotiClient(sdkId, keystream);
            });
        }
コード例 #10
0
        public void YotiClient_NoKeyStream_ThrowsException()
        {
            StreamReader keystream = null;
            string       sdkId     = "fake-sdk-id";

            Assert.ThrowsException <ArgumentNullException>(() =>
            {
                YotiClient client = new YotiClient(sdkId, keystream);
            });
        }
コード例 #11
0
        public void NullAmlProfileShouldThrowException()
        {
            YotiClient client = CreateYotiClient();

            var aggregateException = Assert.ThrowsException <AggregateException>(() =>
            {
                client.PerformAmlCheck(amlProfile: null);
            });

            Assert.IsTrue(TestTools.Exceptions.IsExceptionInAggregateException <ArgumentNullException>(aggregateException));
        }
コード例 #12
0
        public void NullDynamicScenarioShouldThrowException()
        {
            YotiClient client = CreateYotiClient();

            var aggregateException = Assert.ThrowsException <AggregateException>(() =>
            {
                client.CreateShareUrl(null);
            });

            Assert.IsTrue(TestTools.Exceptions.IsExceptionInAggregateException <ArgumentNullException>(aggregateException));
        }
コード例 #13
0
        // GET: Account/Connect?token
        public ActionResult Connect(string token)
        {
            if (token == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            try
            {
                string sdkId = Environment.GetEnvironmentVariable("YOTI_CLIENT_SDK_ID");
                _logger.LogInformation(string.Format("sdkId='{0}'", sdkId));

                string yotiKeyFilePath = Environment.GetEnvironmentVariable("YOTI_KEY_FILE_PATH");
                _logger.LogInformation(
                    string.Format(
                        "yotiKeyFilePath='{0}'",
                        yotiKeyFilePath));

                StreamReader privateKeyStream = System.IO.File.OpenText(yotiKeyFilePath);

                var yotiClient = new YotiClient(sdkId, privateKeyStream);

                ActivityDetails activityDetails = yotiClient.GetActivityDetails(token);

                var profile = activityDetails.Profile;

                ViewBag.RememberMeID = activityDetails.RememberMeId;

                DisplayAttributes displayAttributes = CreateDisplayAttributes(profile.AttributeCollection);

                if (profile.FullName != null)
                {
                    displayAttributes.FullName = profile.FullName.GetValue();
                }

                YotiAttribute <Image> selfie = profile.Selfie;
                if (profile.Selfie != null)
                {
                    displayAttributes.Base64Selfie = selfie.GetValue().GetBase64URI();
                }

                return(View(displayAttributes));
            }
            catch (Exception e)
            {
                _logger.LogError(
                    exception: e,
                    message: e.Message);

                TempData["Error"]          = e.Message;
                TempData["InnerException"] = e.InnerException?.Message;
                return(RedirectToAction("Error"));
            }
        }
コード例 #14
0
        public void ApiUriOverriddenOverEnvVariable()
        {
            Uri overriddenApiUri = new Uri("https://overridden.com");

            Environment.SetEnvironmentVariable("YOTI_API_URL", "https://envapiuri.com");
            YotiClient client = CreateYotiClient();

            client.OverrideApiUri(overriddenApiUri);

            Assert.AreEqual(overriddenApiUri, client.ApiUri);
        }
コード例 #15
0
        public void YotiClient_PerformAmlCheck_NullAmlProfile_ThrowsException()
        {
            string sdkId            = "fake-sdk-id";
            var    privateStreamKey = GetValidKeyStream();

            YotiClient client = new YotiClient(sdkId, privateStreamKey);

            AggregateException aggregateException = Assert.ThrowsException <AggregateException>(() =>
            {
                AmlResult amlResult = client.PerformAmlCheck(amlProfile: null);
            });

            Assert.IsTrue(Exceptions.IsExceptionInAggregateException <ArgumentNullException>(aggregateException));
        }
コード例 #16
0
        public IActionResult DBSStandard()
        {
            try
            {
                string yotiKeyFilePath = Environment.GetEnvironmentVariable("YOTI_KEY_FILE_PATH");
                _logger.LogInformation(
                    string.Format(
                        "yotiKeyFilePath='{0}'",
                        yotiKeyFilePath));

                StreamReader privateKeyStream = System.IO.File.OpenText(yotiKeyFilePath);

                var yotiClient = new YotiClient(_clientSdkId, privateKeyStream);

                DynamicPolicy dynamicPolicy = new DynamicPolicyBuilder()
                                              .WithIdentityProfileRequirements(new
                {
                    trust_framework = "UK_TFIDA",
                    scheme          = new
                    {
                        type      = "DBS",
                        objective = "BASIC"
                    }
                }).Build();

                var dynamicScenario = new DynamicScenarioBuilder()
                                      .WithCallbackEndpoint("/account/connect")
                                      .WithPolicy(dynamicPolicy)
                                      .WithSubject(new
                {
                    subject_id = "some_subject_id_string"
                })
                                      .Build();
                ShareUrlResult shareUrlResult = yotiClient.CreateShareUrl(dynamicScenario);

                ViewBag.YotiClientSdkId = _clientSdkId;

                return(View("DBSCheck", shareUrlResult));
            }
            catch (Exception e)
            {
                _logger.LogError(
                    exception: e,
                    message: e.Message);

                TempData["Error"]          = e.Message;
                TempData["InnerException"] = e.InnerException?.Message;
                return(RedirectToAction("Error", "Account"));
            }
        }
コード例 #17
0
        // GET: Account/Connect?token
        public ActionResult Connect(string token)
        {
            try
            {
                ViewBag.YotiAppId = _appId;
                string sdkId = Environment.GetEnvironmentVariable("YOTI_CLIENT_SDK_ID");
                _logger.LogInformation(string.Format("sdkId='{0}'", sdkId));

                var yotiKeyFilePath = Environment.GetEnvironmentVariable("YOTI_KEY_FILE_PATH");
                _logger.LogInformation(
                    string.Format(
                        "yotiKeyFilePath='{0}'",
                        yotiKeyFilePath));

                var privateKeyStream = System.IO.File.OpenText(yotiKeyFilePath);

                var yotiClient = new YotiClient(sdkId, privateKeyStream);

                var activityDetails = yotiClient.GetActivityDetails(token);
                if (activityDetails.Outcome == ActivityOutcome.Success)
                {
                    _logger.LogInformation("ActivityOutcome=Success");

                    var yotiProfile = activityDetails.Profile;

                    if (yotiProfile.Selfie != null)
                    {
                        PhotoBytes = yotiProfile.Selfie.GetImage().Data;
                    }

                    return(View(yotiProfile));
                }
                else
                {
                    _logger.LogWarning(
                        string.Format(
                            "ActivityOutcome='{0}'",
                            activityDetails.Outcome));
                    return(RedirectToAction("LoginFailure", "Home"));
                }
            }
            catch (Exception e)
            {
                _logger.LogError(
                    exception: e,
                    message: "An error occurred");

                return(RedirectToAction("LoginFailure", "Home"));
            }
        }
コード例 #18
0
        public IActionResult DynamicScenario()
        {
            try
            {
                string yotiKeyFilePath = Environment.GetEnvironmentVariable("YOTI_KEY_FILE_PATH");
                _logger.LogInformation(
                    string.Format(
                        "yotiKeyFilePath='{0}'",
                        yotiKeyFilePath));

                StreamReader privateKeyStream = System.IO.File.OpenText(yotiKeyFilePath);

                var yotiClient = new YotiClient(_clientSdkId, privateKeyStream);

                var givenNamesWantedAttribute = new WantedAttributeBuilder()
                                                .WithName("given_names")
                                                .Build();

                DynamicPolicy dynamicPolicy = new DynamicPolicyBuilder()
                                              .WithWantedAttribute(givenNamesWantedAttribute)
                                              .WithFullName()
                                              .WithSelfie()
                                              .WithPhoneNumber()
                                              .WithAgeOver(18)
                                              .WithRememberMeId(true)
                                              .Build();

                var dynamicScenario = new DynamicScenarioBuilder()
                                      .WithCallbackEndpoint("/account/connect")
                                      .WithPolicy(dynamicPolicy)
                                      .Build();
                ShareUrlResult shareUrlResult = yotiClient.CreateShareUrl(dynamicScenario);

                ViewBag.YotiClientSdkId = _clientSdkId;

                return(View("DynamicScenario", shareUrlResult));
            }
            catch (Exception e)
            {
                _logger.LogError(
                    exception: e,
                    message: e.Message);

                TempData["Error"]          = e.Message;
                TempData["InnerException"] = e.InnerException?.Message;
                return(RedirectToAction("Error", "Account"));
            }
        }
コード例 #19
0
        public void NullAmlAddressShouldThrowException()
        {
            YotiClient client = CreateYotiClient();

            var amlProfile = new AmlProfile(
                givenNames: "Edward Richard George",
                familyName: "Heath",
                amlAddress: null);

            var aggregateException = Assert.ThrowsException <AggregateException>(() =>
            {
                client.PerformAmlCheck(amlProfile: amlProfile);
            });

            Assert.IsTrue(TestTools.Exceptions.IsExceptionInAggregateException <JsonSerializationException>(aggregateException));
        }
コード例 #20
0
ファイル: Program.cs プロジェクト: getyoti/yoti-dotnet-sdk
        private static void Main()
        {
            Console.WriteLine("Yoti AML Example");

            CheckForEnvPresence();

            string sdkId = Environment.GetEnvironmentVariable("YOTI_CLIENT_SDK_ID");

            Console.WriteLine(string.Format("sdkId='{0}'", sdkId));

            string yotiKeyFilePath = Environment.GetEnvironmentVariable("YOTI_KEY_FILE_PATH");

            Console.WriteLine(
                string.Format(
                    "yotiKeyFilePath='{0}'",
                    yotiKeyFilePath));

            using (StreamReader privateKeyStream = File.OpenText(yotiKeyFilePath))
            {
                var yotiClient = new YotiClient(sdkId, privateKeyStream);

                AmlProfile amlProfile;
                if (DotNetEnv.Env.GetBool("USA_EXAMPLE", fallback: false))
                {
                    amlProfile = CreateUsaProfile();
                }
                else
                {
                    amlProfile = CreateGbrProfile();
                }

                AmlResult amlResult = yotiClient.PerformAmlCheck(amlProfile);

                Console.WriteLine(string.Format(
                                      "{0}{0}Completing check for AML profile: '{1}'",
                                      Environment.NewLine,
                                      JsonConvert.SerializeObject(amlProfile, Formatting.Indented)));

                Console.WriteLine(string.Format(
                                      "{0}{0}Result:",
                                      Environment.NewLine));
                Console.WriteLine(string.Format("Is on PEP list: {0}", amlResult.IsOnPepList()));
                Console.WriteLine(string.Format("Is on Fraud list: {0}", amlResult.IsOnFraudList()));
                Console.WriteLine(string.Format("Is on Watch list: {0}", amlResult.IsOnWatchList()));
            }
        }
コード例 #21
0
        public void YotiClient_PerformAmlCheck_NullFamilyName_ThrowsException()
        {
            string sdkId            = "fake-sdk-id";
            var    privateStreamKey = GetValidKeyStream();

            YotiClient client = new YotiClient(sdkId, privateStreamKey);

            AmlProfile amlProfile = new AmlProfile(
                givenNames: "Edward Richard George",
                familyName: null,
                amlAddress: TestTools.Aml.CreateStandardAmlAddress());

            AggregateException aggregateException = Assert.ThrowsException <AggregateException>(() =>
            {
                AmlResult amlResult = client.PerformAmlCheck(amlProfile: amlProfile);
            });

            Assert.IsTrue(Exceptions.IsExceptionInAggregateException <JsonSerializationException>(aggregateException));
        }
コード例 #22
0
        /// <summary>
        /// Initializes a <see cref="YotiAuthenticationMiddleware"/>
        /// </summary>
        /// <param name="next">The next middleware in the OWIN pipeline to invoke</param>
        /// <param name="app">The OWIN application</param>
        /// <param name="options">Configuration options for the middleware</param>
        public YotiAuthenticationMiddleware(
            OwinMiddleware next,
            IAppBuilder app,
            YotiAuthenticationOptions options,
            StreamReader privateKeySteam)
            : base(next, options)
        {
            if (string.IsNullOrWhiteSpace(Options.AppId))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "AppId"));
            }

            if (string.IsNullOrWhiteSpace(Options.SdkId))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "SdkId"));
            }

            if (privateKeySteam == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "PrivateKeyPath"));
            }

            _logger = app.CreateLogger <YotiAuthenticationMiddleware>();

            if (Options.Provider == null)
            {
                Options.Provider = new YotiAuthenticationProvider();
            }
            if (Options.StateDataFormat == null)
            {
                IDataProtector dataProtecter = app.CreateDataProtector(
                    typeof(YotiAuthenticationMiddleware).FullName,
                    Options.AuthenticationType, "v1");
                Options.StateDataFormat = new PropertiesDataFormat(dataProtecter);
            }

            if (String.IsNullOrEmpty(Options.SignInAsAuthenticationType))
            {
                Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType();
            }

            _yotiClient = new YotiClient(Options.SdkId, privateKeySteam);
        }
コード例 #23
0
 public YotiAuthenticationHandler(YotiClient yotiClient, ILogger logger)
 {
     _yotiClient = yotiClient;
     _logger     = logger;
 }
コード例 #24
0
        // GET: Account/Connect?token
        public ActionResult Connect(string token)
        {
            if (token == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            try
            {
                string sdkId            = ConfigurationManager.AppSettings["YOTI_CLIENT_SDK_ID"];
                var    privateKeyStream = System.IO.File.OpenText(ConfigurationManager.AppSettings["YOTI_KEY_FILE_PATH"]);
                var    yotiClient       = new YotiClient(sdkId, privateKeyStream);

                var activityDetails = yotiClient.GetActivityDetails(token);
                if (activityDetails.Outcome == ActivityOutcome.Success)
                {
                    var profile = activityDetails.Profile;

                    User user = UserManager.GetUserByYotiId(profile.Id);

                    if (user == null)
                    {
                        user = new User
                        {
                            YotiId = profile.Id
                        };
                    }

                    if (profile.Selfie != null)
                    {
                        user.Base64Photo = profile.Selfie.GetBase64URI();
                        user.Photo       = profile.Selfie.GetImage().Data;
                        PhotoBytes       = user.Photo;
                    }
                    else
                    {
                        ViewBag.Message = "No photo provided, change the application settings to request a photo from the user for this demo";
                    }

                    UpdateAttributesIfPresent(profile, user);

                    UserManager.SaveUser(user);

                    var identity = new ClaimsIdentity(new[] {
                        new Claim(ClaimTypes.Name, user.Id.ToString()),
                    },
                                                      "ApplicationCookie");

                    var ctx         = Request.GetOwinContext();
                    var authManager = ctx.Authentication;

                    authManager.SignIn(identity);

                    return(View(user));
                }
                else
                {
                    return(RedirectToAction("LoginFailure", "Home"));
                }
            }
            catch (Exception e)
            {
                ViewBag.Error = e.ToString();
                return(RedirectToAction("LoginFailure", "Home"));
            }
        }
コード例 #25
0
 public void YotiClient_ValidParameters_DoesntThrowException()
 {
     StreamReader keystream = GetValidKeyStream();
     string       sdkId     = "fake-sdk-id";
     YotiClient   client    = new YotiClient(sdkId, keystream);
 }
コード例 #26
0
        public void TestProfile()
        {
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair sandboxKeyPair;

            using (StreamReader stream = File.OpenText("path/to/hub-private-key.pem"))
            {
                sandboxKeyPair = Yoti.Auth.CryptoEngine.LoadRsaKey(stream);
            }

            const string sandboxClientSdkid = "your SDK ID";

            SandboxClient sandboxClient = new SandboxClientBuilder()
                                          .WithClientSdkId(sandboxClientSdkid)
                                          .WithKeyPair(sandboxKeyPair)
                                          .Build();

            SandboxAgeVerification ageVerification = new SandboxAgeVerificationBuilder()
                                                     .WithDateOfBirth(new DateTime(2001, 12, 31))
                                                     .WithAgeOver(18)
                                                     .Build();

            DateTime expiryDate = DateTime.UtcNow.AddDays(1);

            var documentImages = new SandboxDocumentImagesBuilder()
                                 .WithJpegContent(Encoding.UTF8.GetBytes("some JPEG content"))
                                 .WithPngContent(Encoding.UTF8.GetBytes("some PNG content"))
                                 .Build();

            SandboxExtraData sandboxExtraData =
                new SandboxExtraDataBuilder()
                .WithDataEntry(
                    new SandboxAttributeIssuanceDetailsBuilder()
                    .WithDefinition("attribute.name")
                    .WithExpiryDate(expiryDate)
                    .WithIssuanceToken("some-issuance-token")
                    .Build())
                .Build();

            YotiTokenRequest tokenRequest = new YotiTokenRequestBuilder()
                                            .WithRememberMeId("some Remember Me ID")
                                            .WithGivenNames("some given names")
                                            .WithFamilyName("some family name")
                                            .WithFullName("some full name")
                                            .WithDateOfBirth(new DateTime(1980, 10, 30))
                                            .WithAgeVerification(ageVerification)
                                            .WithGender("some gender")
                                            .WithPhoneNumber("some phone number")
                                            .WithNationality("some nationality")
                                            .WithStructuredPostalAddress(Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                building_number = 1,
                address_line1   = "some address"
            }))
                                            .WithBase64Selfie(Convert.ToBase64String(Encoding.UTF8.GetBytes("some base64 encoded selfie")))
                                            .WithEmailAddress("some@email")
                                            .WithDocumentDetails("PASSPORT USA 1234abc")
                                            .WithDocumentImages(documentImages)
                                            .WithExtraData(sandboxExtraData)
                                            .Build();

            var sandboxOneTimeUseToken = sandboxClient.SetupSharingProfile(tokenRequest);

            var yotiClient = new YotiClient(new HttpClient(), sandboxClientSdkid, sandboxKeyPair);

            Uri sandboxUri = new UriBuilder(
                "https",
                "api.yoti.com",
                443,
                "sandbox/v1").Uri;

            yotiClient.OverrideApiUri(sandboxUri);

            ActivityDetails activityDetails = yotiClient.GetActivityDetails(sandboxOneTimeUseToken);

            // Perform tests
            Assert.AreEqual("some@email", activityDetails.Profile.EmailAddress.GetValue());
        }