public void TestGetCredential() { // Arrange string expectedNamespace = "LegacyGeneric"; string expectedAttribute = "target"; string expectedTargetAlias = string.Empty; string expectedTargetName = "Unit Test Demo"; CredentialType expectedType = CredentialType.Generic; CredentialPersist expectedPersist = CredentialPersist.LocalMachine; string expectedUsername = "******"; string expectedPassword = "******"; PSCredential expectedCredential = new PSCredential(expectedUsername, CredentialHelper.StringToSecureString(expectedPassword)); // Act CredentialEntry actualCredentialEntry = CredentialStore.GetCredential(expectedTargetName, expectedType); // Assert Assert.AreEqual(expectedNamespace, actualCredentialEntry.Namespace); Assert.AreEqual(expectedAttribute, actualCredentialEntry.Attribute); Assert.AreEqual(expectedTargetAlias, actualCredentialEntry.TargetAlias); Assert.AreEqual(expectedTargetName, actualCredentialEntry.TargetName); Assert.AreEqual(expectedType, actualCredentialEntry.Type); Assert.AreEqual(expectedPersist, actualCredentialEntry.Persist); Assert.AreEqual(expectedUsername, actualCredentialEntry.Credential.UserName); Assert.AreEqual(expectedPassword, actualCredentialEntry.Credential.GetNetworkCredential().Password); }
private void CredentialStoreTest(string url, string username, string password) { try { Uri uri = new Uri(url, UriKind.Absolute); Credentials writeCreds = new Credentials(username, password); Credentials readCreds = null; ICredentialStore priamryStore = new CredentialStore("prime-test"); priamryStore.WriteCredentials(uri, writeCreds); if (priamryStore.ReadCredentials(uri, out readCreds)) { Assert.AreEqual(writeCreds.Password, readCreds.Password, "Passwords did not match between written and read credentials"); Assert.AreEqual(writeCreds.Username, readCreds.Username, "Usernames did not match between written and read credentials"); } else { Assert.Fail("Failed to read credentials"); } priamryStore.DeleteCredentials(uri); Assert.IsFalse(priamryStore.ReadCredentials(uri, out readCreds), "Deleted credentials were read back"); } catch (Exception exception) { Assert.Fail(exception.Message); } }
public async Task BeginAuthorizeAsync() { if (CredentialStore == null) { throw new NullReferenceException( "The authorization process requires a minimum of ConsumerKey and ConsumerSecret tokens. " + "You must assign the CredentialStore property (with tokens) before calling AuthorizeAsync()."); } if (CredentialStore.HasAllCredentials()) { return; } if (string.IsNullOrWhiteSpace(CredentialStore.ConsumerKey) || string.IsNullOrWhiteSpace(CredentialStore.ConsumerSecret)) { throw new ArgumentException("You must populate CredentialStore with ConsumerKey and ConsumerSecret tokens before calling AuthorizeAsync.", "CredentialStore"); } if (GoToTwitterAuthorization == null) { throw new InvalidOperationException("You must provide an Action<string> delegate/lambda for GoToTwitterAuthorization."); } await GetRequestTokenAsync("oob").ConfigureAwait(false); string authUrl = PrepareAuthorizeUrl(ForceLogin); GoToTwitterAuthorization(authUrl); }
/// <summary> /// Sets a <see cref="Credential"/> in the storage used by the authentication object. /// </summary> /// <param name="targetUri"> /// The uniform resource indicator used to uniquely identify the credentials. /// </param> /// <param name="credentials">The value to be stored.</param> public override void SetCredentials(TargetUri targetUri, Credential credentials) { BaseSecureStore.ValidateTargetUri(targetUri); BaseSecureStore.ValidateCredential(credentials); CredentialStore.WriteCredentials(targetUri, credentials); }
public void TestGetCredentials() { // Act IEnumerable <CredentialEntry> actualCredentialEntries = CredentialStore.GetCredentials(); // Assert Assert.AreNotEqual(actualCredentialEntries.Count(), 0); }
public void testGetInvalidCredential() { CredentialStore store = new CredentialStore(); store.LoadFromStream(new FileStream(VALID_FILE, FileMode.Open)); store.Get(INVALID_KEY); }
public async Task Apply(IRequest request) { Credentials credentials = await CredentialStore.GetCredentials().ConfigureAwait(false); BasicAuthenticator basicAuthenticator = new BasicAuthenticator(); basicAuthenticator.Authenticate(request, credentials); }
public void testLoadFromFilePath() { CredentialStore store = new CredentialStore(); store.LoadFromFilePath(VALID_FILE); assertCorrectCredentials(store); }
public async Task Apply(IRequest request) { Ensure.ArgumentIsNotNull(request, "request"); var credentials = await CredentialStore.GetCredentials().ConfigureAwait(false) ?? Credentials.Anonymous; authenticators[credentials.AuthenticationType].Authenticate(request, credentials); }
public async Task Apply(IRequest request) { request.ArgumentNotNull(nameof(request)); var credentials = await CredentialStore.GetCredentials().ConfigureAwait(false) ?? Credentials.Anonymous; Authenticators[credentials.AuthenticationType].Authenticate(request, credentials); }
/// <summary> /// First part of the authorization sequence that: /// 1. Obtains a request token and then /// 2. Redirects to the Twitter authorization page /// </summary> /// <param name="callback">This is where you want Twitter to redirect to after authorization</param> public virtual async Task BeginAuthorizeAsync(Uri callback, Dictionary <string, string> parameters = null) { if (CredentialStore == null) { throw new NullReferenceException( "The authorization process requires a minimum of ConsumerKey and ConsumerSecret tokens. " + "You must assign the CredentialStore property (with tokens) before calling AuthorizeAsync()."); } if (CredentialStore.HasAllCredentials()) { throw new InvalidOperationException( "Your LINQ to Twitter Authorizer already has all credentials assigned to it. In this " + "case, You don't need to re-authorize because having the OAuthToken/AccessToken and " + "OAuthTokenSecret/AccessTokenSecret means that you already have the user's credentials " + "and re-authorization isn't required. If for some reason, these credentials are not " + "working (e.g. the user might have removed your app from their Twitter app list). Set the " + "OAuthToken/AccessToken and OAuthTokenSecret/AccessTokenSecret in the authorizer's credential " + "store to 'null' and then re-authorize. Tip: Call Authorizer.CredentialStore.HasAllCredentials() " + "to see if all of the credentials are already populated. Additionally, if you meant to authorize " + "for a different user, you can call Authorizer.CredentialStore.ClearAsync() to remove the " + "previous user's credentials. (just make sure you've re-loaded your consumerKey and consumerSecret)."); } if (string.IsNullOrWhiteSpace(CredentialStore.ConsumerKey) || string.IsNullOrWhiteSpace(CredentialStore.ConsumerSecret)) { throw new ArgumentException("You must populate CredentialStore with ConsumerKey and ConsumerSecret tokens before calling AuthorizeAsync.", "CredentialStore"); } if (GoToTwitterAuthorization == null) { throw new InvalidOperationException("You must provide an Action<string> delegate/lambda for GoToTwitterAuthorization."); } string callbackString = callback.ToString(); if (parameters != null) { var paramsList = new List <string>(); foreach (var parm in parameters) { Parameters.Add(parm); paramsList.Add($"{parm.Key}={parm.Value}"); } string queryString = "?" + string.Join("&", paramsList); OAuthRequestTokenUrl += queryString; callbackString += queryString; } await GetRequestTokenAsync(callbackString).ConfigureAwait(false); string authUrl = PrepareAuthorizeUrl(ForceLogin); GoToTwitterAuthorization(authUrl); }
public void BeforeEachTest() { Client.Arrange(cl => cl.GetRawResultOfBasicGetRequest(Arg.AnyString)).Returns(SearchResult); var store = new CredentialStore($"ApiKey:{ApiKey}\nCseId:{CustomSearchEngineId}"); Target = new SearchResultRetriever(Client, store); Target.Delay = i => { }; }
public void testLoadFromInputStream() { CredentialStore store = new CredentialStore(); FileStream testStream = new FileStream(VALID_FILE, FileMode.Open); store.LoadFromStream(testStream); assertCorrectCredentials(store); }
static ProxySettingsView CreateDialog() { var credentialStore = new CredentialStore(); var proxyTester = new ProxyTester(credentialStore); return(new ProxySettingsView(proxyTester, credentialStore) { Owner = ShellView.CurrentInstance }); }
public RuntimeUpgradeManager(IEventAggregator eventAggregator, CredentialStore credentialStore, ProcessRunner processRunner) { this.eventAggregator = eventAggregator; this.credentialStore = credentialStore; this.processRunner = processRunner; var tempFolder = new DirectoryInfo(Environment.ExpandEnvironmentVariables("%temp%")); var assetFolder = Directory.CreateDirectory(Path.Combine(tempFolder.FullName, @"Particular\PlatformInstaller")); installer = new FileInfo(Path.Combine(assetFolder.FullName, dotNet452WebInstallerExe)); }
public async Task ExplicitGetInvokeUsingClient() { using (dynamic client = new DynamicRestClient("http://openstates.org/api/v1/", MockInitialization.Handler)) { string key = CredentialStore.RetrieveObject("sunlight.key.json").Key; dynamic result = await client.metadata.mn.get(apikey : key); Assert.IsNotNull(result); Assert.AreEqual("Minnesota", result.name); } }
public async Task EscapeUriSegmentsUsingClient() { using (dynamic client = new DynamicRestClient("http://openstates.org/api/v1/", MockInitialization.Handler)) { string key = CredentialStore.RetrieveObject("sunlight.key.json").Key; var result = await client.bills.mn("2013s1")("SF 1").get(apikey: key); Assert.IsNotNull(result); Assert.IsTrue(result.id == "MNB00017167"); } }
private void assertCorrectCredentials(CredentialStore store) { Assert.AreEqual(KEYS[0], store.Get(KEYS[1]).SecretKey); Assert.AreEqual(KEYS[1], store.Get(KEYS[1]).PublicKey); Assert.AreEqual(KEYS[2], store.Get(KEYS[3]).SecretKey); Assert.AreEqual(KEYS[3], store.Get(KEYS[3]).PublicKey); Assert.AreEqual(KEYS[4], store.Get(KEYS[5]).SecretKey); Assert.AreEqual(KEYS[5], store.Get(KEYS[5]).PublicKey); }
/// <summary> /// Not required. Since you've already provided all 4 tokens, you don't need to call this. /// </summary> public async Task AuthorizeAsync() { if (!CredentialStore.HasAllCredentials()) { throw new InvalidOperationException("SingleUserAuthorizer needs pre-set credentials; don't call Authorize unless you've set all four credentials."); } await Task.Delay(0).ConfigureAwait(false); return; }
public virtual void Initialize(CredentialStore credentialStore) { var serializer = new ManateeSerializer(); TrelloConfiguration.Serializer = serializer; TrelloConfiguration.Deserializer = serializer; TrelloConfiguration.JsonFactory = new ManateeFactory(); TrelloConfiguration.RestClientProvider = new WebApiClientProvider(); Auth.AppKey = credentialStore["TrelloAppKey"]; Auth.UserToken = credentialStore["TrelloUserToken"]; }
public void TestExistCredential() { // Arrange string targetName = "Unit Test Demo"; CredentialType type = CredentialType.Generic; // Act Boolean exists = CredentialStore.ExistCredential(targetName, type); // Assert Assert.IsTrue(exists); }
public async Task ReservedWordNameEscapeWithCSharpSyntax() { using (dynamic client = new DynamicRestClient("http://openstates.org/api/v1/", MockInitialization.Handler)) { string key = CredentialStore.RetrieveObject("sunlight.key.json").Key; //escape the reserved word "long" with an @ symbol var result = await client.legislators.geo.get(apikey : key, lat : 44.926868, @long : -93.214049); Assert.IsNotNull(result); Assert.IsTrue(result.Count > 0); } }
public ShellViewModel(IEventAggregator eventAggregator, LicenseAgreement licenseAgreement, ILifetimeScope lifetimeScope, RaygunClient raygunClient, Installer installer, ProxyTester proxyTester, RuntimeUpgradeManager runtimeUpgradeManager, CredentialStore credentialStore) { DisplayName = "Platform Installer"; this.runtimeUpgradeManager = runtimeUpgradeManager; this.raygunClient = raygunClient; this.installer = installer; this.licenseAgreement = licenseAgreement; this.lifetimeScope = lifetimeScope; this.eventAggregator = eventAggregator; this.proxyTester = proxyTester; this.credentialStore = credentialStore; RunStartupSequence(); }
public async Task ExplicitGetInvoke() { var client = new RestClient("http://openstates.org/api/v1"); string key = CredentialStore.RetrieveObject("sunlight.key.json").Key; client.AddDefaultHeader("X-APIKEY", key); dynamic proxy = new RestSharpProxy(client); dynamic result = await proxy.metadata.mn.get(); Assert.IsNotNull(result); Assert.IsTrue(result.name == "Minnesota"); }
public async Task GetMethodSegmentWithArgs() { var client = new RestClient("http://openstates.org/api/v1"); string key = CredentialStore.RetrieveObject("sunlight.key.json").Key; client.AddDefaultHeader("X-APIKEY", key); dynamic proxy = new RestSharpProxy(client); var result = await proxy.bills.mn("2013s1")("SF 1").get(); Assert.IsNotNull(result); Assert.IsTrue(result.id == "MNB00017167"); }
public void testLoadFromString() { CredentialStore store = new CredentialStore(); FileStream stream = new FileStream(VALID_FILE, FileMode.Open); StreamReader reader = new StreamReader(stream); string contents = reader.ReadToEnd(); reader.Close(); store.LoadFromContents(contents); assertCorrectCredentials(store); }
/// <summary> /// Adds the SAML token as a header to the request if it is already cached for this host. /// </summary> public static void PrepareSTSRequest( Uri feedUri, CredentialStore credentialStore, HttpRequestMessage request) { #if !IS_CORECLR var credentials = credentialStore.GetCredentials(feedUri) as STSCredentials; if (credentials != null) { request.Headers.TryAddWithoutValidation(STSTokenHeader, credentials.STSToken); } #endif }
public override async void OnUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { var me = new ComponentName(context, Java.Lang.Class.FromType(typeof(AppWidget)).Name); var widgetView = new RemoteViews(context.PackageName, Resource.Layout.Widget); InternetStatus status = new InternetStatus(); NetCredential credential = new NetCredential(); (credential.Username, credential.Password) = await CredentialStore.LoadCredentialAsync(); credential.State = await status.SuggestAsync(); NetXFSettings settings = new NetXFSettings(); settings.LoadSettings(); var helper = credential.GetHelper(settings); if (helper != null) { if (settings.BackgroundAutoLogin && !string.IsNullOrEmpty(credential.Username)) { if (settings.EnableRelogin) { await helper.LogoutAsync(); } await helper.LoginAsync(); } FluxUser user = await helper.GetFluxAsync(); var remainFlux = FluxHelper.GetMaxFlux(user.Flux, user.Balance) - user.Flux; widgetView.SetTextViewText(Resource.Id.widgetTitle, $"用户:{user.Username}"); widgetView.SetTextViewText(Resource.Id.widgetFlux, $"流量:{user.Flux}"); widgetView.SetTextViewText(Resource.Id.widgetRemain, $"剩余:{remainFlux}"); widgetView.SetTextViewText(Resource.Id.widgetBalance, string.Format(CultureInfo.GetCultureInfo("zh-CN"), "余额:{0:C2}", user.Balance)); } else { widgetView.SetTextViewText(Resource.Id.widgetTitle, "暂无流量信息"); widgetView.SetTextViewText(Resource.Id.widgetFlux, string.Empty); widgetView.SetTextViewText(Resource.Id.widgetRemain, string.Empty); widgetView.SetTextViewText(Resource.Id.widgetBalance, string.Empty); } var intent = new Intent(context, typeof(AppWidget)); intent.SetAction(AppWidgetManager.ActionAppwidgetUpdate); intent.PutExtra(AppWidgetManager.ExtraAppwidgetIds, appWidgetIds); var piBackground = PendingIntent.GetBroadcast(context, 0, intent, PendingIntentFlags.UpdateCurrent); widgetView.SetOnClickPendingIntent(Resource.Id.widgetBackground, piBackground); appWidgetManager.UpdateAppWidget(me, widgetView); }
public async Task GetMethod1PathArg1Param() { var client = new RestClient("http://openstates.org/api/v1"); string key = CredentialStore.RetrieveObject("sunlight.key.json").Key; client.AddDefaultHeader("X-APIKEY", key); dynamic proxy = new RestSharpProxy(client); var result = await proxy.bills.get(state : "mn", chamber : "upper", status : "passed_upper"); Assert.IsNotNull(result); Assert.IsNotNull(result.Count > 0); Assert.IsTrue(result[0].chamber == "upper"); }
/// <summary> /// Creates a credential parameter from a string only. Will prompt the user for the rest of the input. Will provide an option to remember the credential under the name provided /// </summary> /// <param name="UserName">The username (and domain name as may be the case) to put a credential around</param> public DbaCredentialParameter(string UserName) { if (CredentialStore.ContainsKey(UserName.ToLower())) { Credential = CredentialStore[UserName.ToLower()]; } else if (dbaSystem.SystemHost.UnattendedMode) { throw new InvalidOperationException("Cannot prompt for credentials in unattended mode!"); } else { Credential = PromptForCredential(UserName); } }
public async Task UploadPhoto() { var key = CredentialStore.RetrieveObject("flickr.key.json"); var defaults = new DynamicRestClientDefaults(); defaults.DefaultParameters.Add("format", "json"); defaults.DefaultParameters.Add("api_key", key.Key); defaults.DefaultParameters.Add("nojsoncallback", "1"); dynamic client = new DynamicRestClient("https://up.flickr.com/services/", defaults); dynamic result = await client.upload.post(photo : File.OpenRead(@"D:\temp\test.png")); Assert.IsNotNull(result); }