public Merchant(NodeWrapper node) { if (node == null) return; NodeWrapper merchantNode = node.GetNode("merchant"); Id = merchantNode.GetString("id"); Email = merchantNode.GetString("email"); CompanyName = merchantNode.GetString("company-name"); CountryCodeAlpha3 = merchantNode.GetString("country-code-alpha3"); CountryCodeAlpha2 = merchantNode.GetString("country-code-alpha2"); CountryCodeNumeric = merchantNode.GetString("country-code-numeric"); CountryName = merchantNode.GetString("country-name"); Credentials = new OAuthCredentials(node.GetNode("credentials")); var merchantAccountXmlNodes = merchantNode.GetList("merchant-accounts/merchant-account"); MerchantAccounts = new MerchantAccount[merchantAccountXmlNodes.Count]; for (int i = 0; i < merchantAccountXmlNodes.Count; i++) { MerchantAccounts[i] = new MerchantAccount(merchantAccountXmlNodes[i]); } }
public EndpointResolver(IUrlResolver urlResolver, OAuthCredentials consumerCredentials) { _consumerCredentials = consumerCredentials; _urlResolver = urlResolver; }
private Token Authenticate(OAuthCredentials credentials) { if (credentials == null) { throw new AuthFailedException("Missing credentials"); } SecucardTrace.Info("Authenticate credentials: {0}", credentials.ToString()); var pollInterval = 0; var timeout = DateTime.Now; var devicesCredentials = credentials as DeviceCredentials; var isDeviceAuth = (devicesCredentials != null); DeviceAuthCode codes = null; // if DeviceAuth then get codes an pass to app thru event. Further action required by client if (isDeviceAuth) { codes = _rest.GetDeviceAuthCode(devicesCredentials.ClientId, devicesCredentials.ClientSecret, devicesCredentials.DeviceId); if (TokenManagerStatusUpdateEvent != null) { TokenManagerStatusUpdateEvent.Invoke(this, new TokenManagerStatusUpdateEventArgs { DeviceAuthCodes = codes, Status = AuthStatusEnum.Pending }); } SecucardTrace.Info("Retrieved codes for device auth: {0}, now polling for auth.", codes); // set poll timeout, either by config or by expire time of code var t = codes.ExpiresIn; if (t <= 0 || _config.AuthWaitTimeoutSec < t) { t = _config.AuthWaitTimeoutSec; } timeout = DateTime.Now.AddSeconds(t * 1000); pollInterval = codes.Interval; if (pollInterval <= 0) { pollInterval = 5; // poll default 5s } devicesCredentials.DeviceCode = codes.DeviceCode; devicesCredentials.DeviceId = null; // device id must be empty for next auth. step! } do { Token token = null; if (isDeviceAuth) { // in case of device auth, check for cancel and delay polling if (CancelAuthFlag) { throw new AuthCanceledException("Authorization canceled by request."); } Thread.Sleep(pollInterval * 1000); token = _rest.ObtainAuthToken(codes.DeviceCode, devicesCredentials.ClientId, devicesCredentials.ClientSecret); if (token == null) // auth not completed yet { OnTokenManagerStatusUpdateEvent(new TokenManagerStatusUpdateEventArgs { DeviceAuthCodes = codes, Status = AuthStatusEnum.Pending }); } } else { var clientCredentials = credentials as ClientCredentials; if (clientCredentials != null) { token = _rest.GetToken(clientCredentials.ClientId, clientCredentials.ClientSecret); } } if (token != null) { return(token); } } while (DateTime.Now < timeout); if (isDeviceAuth) { throw new AuthTimeoutException(); } throw new System.Exception("Unexpected failure of authentication."); }
private void m_fpPrefForm_CredentialsAdded(object sender, OAuthCredentials oaCredentials) { TwitterController.GetController().AddNewAccount(oaCredentials); }
// Token: 0x060014EC RID: 5356 RVA: 0x00077EBE File Offset: 0x000760BE public static ICredentials GetOAuthCredentials(ADUser user) { return(OAuthCredentials.GetOAuthCredentialsForAppActAsToken(user.OrganizationId, user, null)); }
/// <summary> /// Activates this API instance using previously acquired access keys. This function does not verify the /// authenticity of these keys - use OAuth() or XAuth() instead. This function copies the supplied keys /// and uses them to sign requests. /// </summary> /// <param name="oaCredentials">The user's credentials, initially provided by Twitter's auth system.</param> public OAuthCredentials GetCredentials(OAuthCredentials oaCredentials) { oaCredentials.Type = OAuthType.ProtectedResource; return(oaCredentials); }
public Dictionary <GroupId, List <MailboxInfo> > FindEwsEndpoints(out long localDiscoverTime, out long autoDiscoverTime) { Stopwatch stopwatch = new Stopwatch(); localDiscoverTime = 0L; autoDiscoverTime = 0L; stopwatch.Start(); List <MailboxInfo> list; string text; this.FilterLocalForestMailboxes(out list, out text); stopwatch.Stop(); localDiscoverTime = stopwatch.ElapsedMilliseconds; Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, long>((long)this.GetHashCode(), "Correlation Id:{0}. Mapping local mailboxes to servers took {1}ms", this.callerInfo.QueryCorrelationId, localDiscoverTime); if (list == null || list.Count == 0) { return(this.mailboxGroups); } string searchId = string.Empty; Match match = Regex.Match(this.callerInfo.UserAgent, "SID=([a-fA-F0-9\\-]*)"); if (match.Success && match.Groups != null && match.Groups.Count > 1) { searchId = match.Groups[1].Value; } Uri url = null; EndPointDiscoveryInfo endPointDiscoveryInfo; bool flag = RemoteDiscoveryEndPoint.TryGetDiscoveryEndPoint(this.orgId, text, this.GetOrgIdCacheValue, this.GetIntraOrganizationConnector, this.GetOrganizationRelationShip, out url, out endPointDiscoveryInfo); if (endPointDiscoveryInfo != null && endPointDiscoveryInfo.Status != EndPointDiscoveryInfo.DiscoveryStatus.Success) { SearchEventLogger.Instance.LogSearchErrorEvent(searchId, endPointDiscoveryInfo.Message); } if (!flag) { Factory.Current.MailboxGroupGeneratorTracer.TraceDebug <Guid, string>((long)this.GetHashCode(), "Correlation Id:{0}. Unable to find the discovery end point for domain {1}", this.callerInfo.QueryCorrelationId, text); GroupId key = new GroupId(new MultiMailboxSearchException(Strings.CouldNotFindOrgRelationship(text))); this.mailboxGroups.Add(key, list); return(this.mailboxGroups); } Factory.Current.MailboxGroupGeneratorTracer.TraceDebug <Guid, string, Uri>((long)this.GetHashCode(), "Correlation Id:{0}. EWS endpoint for domain {1} is {2}", this.callerInfo.QueryCorrelationId, text, EwsWsSecurityUrl.FixForAnonymous(url)); OAuthCredentials oauthCredentialsForAppToken = OAuthCredentials.GetOAuthCredentialsForAppToken(this.orgId, text); stopwatch.Restart(); List <MailboxInfo> list2 = (from mailboxInfo in list where mailboxInfo.IsArchive select mailboxInfo).ToList <MailboxInfo>(); List <MailboxInfo> list3 = (from mailboxInfo in list where !mailboxInfo.IsArchive select mailboxInfo).ToList <MailboxInfo>(); if (list2.Count > 0) { Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, int>((long)this.GetHashCode(), "Correlation Id:{0}. Mbx Count:{1}. Autodiscover started for cross premise archive mailboxes.", this.callerInfo.QueryCorrelationId, list2.Count); this.DoAutodiscover(list2, EwsWsSecurityUrl.FixForAnonymous(url), oauthCredentialsForAppToken); Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, int>((long)this.GetHashCode(), "Correlation Id:{0}. Mbx Count:{1}. Autodiscover completed for cross premise archive mailboxes.", this.callerInfo.QueryCorrelationId, list2.Count); } if (list3.Count > 0) { Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, int>((long)this.GetHashCode(), "Correlation Id:{0}. Mbx Count:{1}. Autodiscover started for cross premise primary mailboxes.", this.callerInfo.QueryCorrelationId, list3.Count); this.DoAutodiscover(list3, EwsWsSecurityUrl.FixForAnonymous(url), oauthCredentialsForAppToken); Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, int>((long)this.GetHashCode(), "Correlation Id:{0}. Mbx Count:{1}. Autodiscover completed for cross premise primary mailboxes.", this.callerInfo.QueryCorrelationId, list3.Count); } stopwatch.Stop(); autoDiscoverTime = stopwatch.ElapsedMilliseconds; Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, long>((long)this.GetHashCode(), "Correlation Id:{0}. Autodiscover call took {1}ms", this.callerInfo.QueryCorrelationId, autoDiscoverTime); return(this.mailboxGroups); }
public async Task <IActionResult> AddTwitterAccount(bool follow) { int count = 0; string profileCount = ""; List <Domain.Socioboard.Models.Groups> groups = new List <Domain.Socioboard.Models.Groups>(); Domain.Socioboard.Models.User user = HttpContext.Session.GetObjectFromJson <Domain.Socioboard.Models.User>("User"); HttpResponseMessage response = await WebApiReq.GetReq("/api/Groups/GetUserGroups?userId=" + user.Id, "", "", _appSettings.ApiDomain); if (response.IsSuccessStatusCode) { try { groups = await response.Content.ReadAsAsync <List <Domain.Socioboard.Models.Groups> >(); } catch { } } string sessionSelectedGroupId = HttpContext.Session.GetObjectFromJson <string>("selectedGroupId"); if (!string.IsNullOrEmpty(sessionSelectedGroupId)) { HttpResponseMessage groupProfilesResponse = await WebApiReq.GetReq("/api/GroupProfiles/GetGroupProfiles?groupId=" + sessionSelectedGroupId, "", "", _appSettings.ApiDomain); if (groupProfilesResponse.IsSuccessStatusCode) { List <Domain.Socioboard.Models.Groupprofiles> groupProfiles = await groupProfilesResponse.Content.ReadAsAsync <List <Domain.Socioboard.Models.Groupprofiles> >(); profileCount = groupProfiles.Count.ToString(); } } else { long selectedGroupId = groups.FirstOrDefault(t => t.groupName == Domain.Socioboard.Consatants.SocioboardConsts.DefaultGroupName).id; HttpContext.Session.SetObjectAsJson("selectedGroupId", selectedGroupId); ViewBag.selectedGroupId = selectedGroupId; HttpResponseMessage groupProfilesResponse = await WebApiReq.GetReq("/api/GroupProfiles/GetGroupProfiles?groupId=" + selectedGroupId, "", "", _appSettings.ApiDomain); if (groupProfilesResponse.IsSuccessStatusCode) { List <Domain.Socioboard.Models.Groupprofiles> groupProfiles = await groupProfilesResponse.Content.ReadAsAsync <List <Domain.Socioboard.Models.Groupprofiles> >(); profileCount = groupProfiles.Count.ToString(); } } // string profileCount = await ProfilesHelper.GetUserProfileCount(user.Id, _appSettings, _logger); try { count = Convert.ToInt32(profileCount); } catch (Exception ex) { TempData["Error"] = "Error while getting profile count."; return(RedirectToAction("Index", "Home")); } int MaxCount = Domain.Socioboard.Helpers.SBHelper.GetMaxProfileCount(user.AccountType); if (count >= MaxCount) { TempData["Error"] = "Max profile Count reached."; return(RedirectToAction("Index", "Home")); } else { if (follow) { HttpContext.Session.SetObjectAsJson("Twitter", "Twitter_Account_Follow"); } else { HttpContext.Session.SetObjectAsJson("Twitter", "Twitter_Account"); } OAuthCredentials credentials = new OAuthCredentials() { Type = OAuthType.RequestToken, SignatureMethod = OAuthSignatureMethod.HmacSha1, ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, ConsumerKey = _appSettings.twitterConsumerKey, ConsumerSecret = _appSettings.twitterConsumerScreatKey, CallbackUrl = _appSettings.twitterRedirectionUrl }; // Use Hammock to create a rest client var client = new RestClient { Authority = "https://api.twitter.com/oauth", Credentials = credentials, }; // Use Hammock to create a request var request = new RestRequest { Path = "request_token" }; // Get the response from the request var _response = client.Request(request); var collection = HttpUtility.ParseQueryString(_response.Content); //string str = collection[1].ToString(); //HttpContext.Current.Session["requestSecret"] = collection[1]; string rest = "https://api.twitter.com/oauth/authorize?oauth_token=" + collection[0]; HttpContext.Session.SetObjectAsJson("requestSecret", collection[1]); return(Redirect(rest)); } }
public static ResultType SendSPOAuthRequest(ADUser user, Uri targetUri, out string diagnosticMessage, bool appOnly = false, bool useCachedToken = false, bool reloadConfig = false) { int startIndex = user.GetFederatedIdentity().Identity.IndexOf('@') + 1; string domain = user.GetFederatedIdentity().Identity.Substring(startIndex); ICredentials icredentials = TestOAuthConnectivityHelper.GetICredentials(appOnly, user, domain); OAuthCredentials oauthCredentials = icredentials as OAuthCredentials; if (icredentials == null) { diagnosticMessage = Strings.NullUserError; return(ResultType.Error); } Guid value = Guid.NewGuid(); oauthCredentials.ClientRequestId = new Guid?(value); ValidationResultCollector resultCollector = new ValidationResultCollector(); LocalConfiguration localConfiguration = LocalConfiguration.Load(resultCollector); oauthCredentials.Tracer = new TestOAuthConnectivityHelper.TaskOauthOutboundTracer(); oauthCredentials.LocalConfiguration = localConfiguration; string text = targetUri.Scheme + "://" + targetUri.Host + "/_vti_bin/listdata.svc"; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(text); httpWebRequest.Method = "GET"; httpWebRequest.ContentType = "text/xml"; httpWebRequest.Headers.Add("X-ExCompId", "OauthPartnerProbe:"); httpWebRequest.Headers.Add("client-request-id", value.ToString()); httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer"); httpWebRequest.UserAgent = "AMProbe/OAUTH/Sharepoint"; httpWebRequest.Credentials = icredentials; httpWebRequest.PreAuthenticate = true; string value2 = string.Empty; StringBuilder stringBuilder = new StringBuilder(1024); stringBuilder.AppendLine(Strings.ClientRequestId(value.ToString())); string value3 = TestOAuthConnectivityHelper.CheckReloadConfig(reloadConfig); string value4 = TestOAuthConnectivityHelper.CheckUseCachedToken(useCachedToken); stringBuilder.AppendLine(value3); stringBuilder.AppendLine(value4); HttpWebResponse httpWebResponse = null; ResultType result = ResultType.Success; string text2 = string.Empty; try { stringBuilder.AppendLine(Strings.OAuthRequestEndPoint(text)); httpWebResponse = (httpWebRequest.GetResponse() as HttpWebResponse); if (httpWebResponse != null && httpWebResponse.StatusCode != HttpStatusCode.OK) { throw new Exception(Strings.HttpWebRequestFailure(httpWebResponse.StatusCode.ToString())); } using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream())) { value2 = streamReader.ReadToEnd(); } } catch (WebException ex) { text2 = ex.ToString(); result = ResultType.Error; } finally { if (httpWebResponse != null) { TestOAuthConnectivityHelper.LogHttpResponseHeaders(httpWebResponse.Headers, ref stringBuilder); } if (httpWebResponse != null) { httpWebResponse.Close(); } } stringBuilder.AppendLine(Strings.TestOutboundOauthLog); stringBuilder.AppendLine(Strings.TestOAuthResponseDetails("SharePoint")); stringBuilder.AppendLine(oauthCredentials.Tracer.ToString()); stringBuilder.AppendLine(Strings.ResponseHeader); stringBuilder.AppendLine(value2); if (text2 != string.Empty) { stringBuilder.AppendLine(Strings.ExceptionHeader); stringBuilder.AppendLine(text2); } diagnosticMessage = stringBuilder.ToString(); return(result); }
public static ResultType SendLyncOAuthRequest(ADUser user, Uri targetUri, out string diagnosticMessage, bool appOnly = false, bool useCachedToken = false, bool reloadConfig = false) { int startIndex = user.GetFederatedIdentity().Identity.IndexOf('@') + 1; string domain = user.GetFederatedIdentity().Identity.Substring(startIndex); StringBuilder stringBuilder = new StringBuilder(); ICredentials icredentials = TestOAuthConnectivityHelper.GetICredentials(appOnly, user, domain); OAuthCredentials oauthCredentials = icredentials as OAuthCredentials; string text = string.Empty; foreach (ProxyAddress proxyAddress in user.EmailAddresses) { if (proxyAddress.ToString().Contains("sip:")) { text = TestOAuthConnectivityHelper.FromSipFormat(proxyAddress.ToString()); } } if (string.IsNullOrEmpty(text)) { text = user.PrimarySmtpAddress.ToString(); } if (string.IsNullOrEmpty(text)) { diagnosticMessage = Strings.EMailAddressNotFound(user.Alias); return(ResultType.Error); } Guid value = Guid.NewGuid(); oauthCredentials.ClientRequestId = new Guid?(value); stringBuilder.AppendLine(Strings.ClientRequestId(value.ToString())); string value2 = TestOAuthConnectivityHelper.CheckReloadConfig(reloadConfig); string value3 = TestOAuthConnectivityHelper.CheckUseCachedToken(useCachedToken); stringBuilder.AppendLine(value2); stringBuilder.AppendLine(value3); ValidationResultCollector resultCollector = new ValidationResultCollector(); LocalConfiguration localConfiguration = LocalConfiguration.Load(resultCollector); oauthCredentials.Tracer = new TestOAuthConnectivityHelper.TaskOauthOutboundTracer(); oauthCredentials.LocalConfiguration = localConfiguration; LyncAnonymousAutodiscoverResult lyncAnonymousAutodiscoverResult = null; try { lyncAnonymousAutodiscoverResult = LyncAutodiscoverWorker.GetAuthenticatedAutodiscoverEndpoint(text, domain); } catch (WebException ex) { stringBuilder.AppendLine(Strings.DiagnosticsHeader); stringBuilder.AppendLine(lyncAnonymousAutodiscoverResult.DiagnosticInfo); stringBuilder.AppendLine(Strings.AutodiscoverFailure); stringBuilder.AppendLine(Strings.TestOutboundOauthLog); stringBuilder.AppendLine(oauthCredentials.Tracer.ToString()); stringBuilder.AppendLine(ex.ToString()); diagnosticMessage = stringBuilder.ToString(); return(ResultType.Error); } catch (Exception ex2) { stringBuilder.AppendLine(Strings.DiagnosticsHeader); stringBuilder.AppendLine(lyncAnonymousAutodiscoverResult.DiagnosticInfo); stringBuilder.AppendLine(Strings.AutodiscoverFailure); stringBuilder.AppendLine(Strings.TestOutboundOauthLog); stringBuilder.AppendLine(oauthCredentials.Tracer.ToString()); stringBuilder.AppendLine(ex2.ToString()); diagnosticMessage = stringBuilder.ToString(); return(ResultType.Error); } if (string.IsNullOrEmpty(lyncAnonymousAutodiscoverResult.AuthenticatedServerUri)) { stringBuilder.AppendLine(Strings.DiagnosticsHeader); stringBuilder.AppendLine(lyncAnonymousAutodiscoverResult.DiagnosticInfo); stringBuilder.AppendLine(Strings.TestOutboundOauthLog); stringBuilder.AppendLine(Strings.NoAuthenticatedServerUri); stringBuilder.AppendLine(oauthCredentials.Tracer.ToString()); diagnosticMessage = stringBuilder.ToString(); return(ResultType.Error); } stringBuilder.AppendLine(Strings.DiagnosticsHeader); stringBuilder.AppendLine(lyncAnonymousAutodiscoverResult.DiagnosticInfo); LyncAutodiscoverResult lyncAutodiscoverResult = null; try { lyncAutodiscoverResult = LyncAutodiscoverWorker.GetUcwaUrl(lyncAnonymousAutodiscoverResult.AuthenticatedServerUri, icredentials); } catch (WebException ex3) { stringBuilder.AppendLine(Strings.DiagnosticsHeader); stringBuilder.AppendLine(lyncAnonymousAutodiscoverResult.DiagnosticInfo); stringBuilder.AppendLine(Strings.UCWADiscoveryUrlException); stringBuilder.AppendLine(lyncAutodiscoverResult.Response); stringBuilder.AppendLine(Strings.TestOutboundOauthLog); stringBuilder.AppendLine(oauthCredentials.Tracer.ToString()); stringBuilder.AppendLine(ex3.ToString()); diagnosticMessage = stringBuilder.ToString(); return(ResultType.Error); } catch (Exception ex4) { stringBuilder.AppendLine(Strings.DiagnosticsHeader); stringBuilder.AppendLine(lyncAnonymousAutodiscoverResult.DiagnosticInfo); stringBuilder.AppendLine(Strings.UCWADiscoveryUrlException); stringBuilder.AppendLine(lyncAutodiscoverResult.Response); stringBuilder.AppendLine(Strings.TestOutboundOauthLog); stringBuilder.AppendLine(oauthCredentials.Tracer.ToString()); stringBuilder.AppendLine(ex4.ToString()); diagnosticMessage = stringBuilder.ToString(); return(ResultType.Error); } if (string.IsNullOrEmpty(lyncAutodiscoverResult.UcwaDiscoveryUrl)) { stringBuilder.AppendLine(Strings.DiagnosticsHeader); stringBuilder.AppendLine(lyncAnonymousAutodiscoverResult.DiagnosticInfo); stringBuilder.AppendLine(Strings.TestOutboundOauthLog); stringBuilder.AppendLine(Strings.UCWADiscoveryUrlEmpty); stringBuilder.AppendLine(lyncAutodiscoverResult.Response); stringBuilder.AppendLine(oauthCredentials.Tracer.ToString()); diagnosticMessage = stringBuilder.ToString(); return(ResultType.Error); } stringBuilder.AppendLine(Strings.DiagnosticsHeader); stringBuilder.AppendLine(lyncAnonymousAutodiscoverResult.DiagnosticInfo); stringBuilder.AppendLine(Strings.TestOutboundOauthLog); stringBuilder.AppendLine(oauthCredentials.Tracer.ToString()); diagnosticMessage = stringBuilder.ToString(); return(ResultType.Success); }
public static ResultType SendGenericOAuthRequest(ADUser user, string orgDomain, Uri targetUri, out string diagnosticMessage, bool appOnly = false, bool useCachedToken = false, bool reloadConfig = false) { string domain = TestOAuthConnectivityHelper.GetDomain(user, orgDomain); if (domain == null) { diagnosticMessage = Strings.NullUserError; return(ResultType.Error); } ICredentials icredentials = TestOAuthConnectivityHelper.GetICredentials(appOnly, user, domain); OAuthCredentials oauthCredentials = icredentials as OAuthCredentials; if (icredentials == null) { diagnosticMessage = Strings.NullUserError; return(ResultType.Error); } ValidationResultCollector resultCollector = new ValidationResultCollector(); LocalConfiguration localConfiguration = LocalConfiguration.Load(resultCollector); oauthCredentials.Tracer = new TestOAuthConnectivityHelper.TaskOauthOutboundTracer(); oauthCredentials.LocalConfiguration = localConfiguration; Guid value = Guid.NewGuid(); oauthCredentials.ClientRequestId = new Guid?(value); HttpWebResponse httpWebResponse = null; ResultType result = ResultType.Success; string text = string.Empty; string s = string.Empty; StringBuilder stringBuilder = new StringBuilder(); string value2 = TestOAuthConnectivityHelper.CheckReloadConfig(reloadConfig); string value3 = TestOAuthConnectivityHelper.CheckUseCachedToken(useCachedToken); stringBuilder.AppendLine(value2); stringBuilder.AppendLine(value3); try { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri(targetUri.ToString())); httpWebRequest.Method = "GET"; httpWebRequest.ContentType = "text/xml"; httpWebRequest.Headers.Add("X-ExCompId", "OauthPartnerProbe:"); httpWebRequest.Headers.Add("client-request-id", value.ToString()); httpWebRequest.Headers.Add("request-id", value.ToString()); httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer"); httpWebRequest.UserAgent = "AMProbe/OAUTH/Exchange"; httpWebRequest.Credentials = icredentials; httpWebResponse = (httpWebRequest.GetResponse() as HttpWebResponse); if (httpWebResponse != null && httpWebResponse.StatusCode != HttpStatusCode.OK) { throw new Exception(Strings.ResponseMessage(httpWebResponse.StatusCode.ToString())); } using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream())) { s = streamReader.ReadToEnd(); } } catch (Exception ex) { text = ex.ToString(); result = ResultType.Error; } finally { if (httpWebResponse != null) { TestOAuthConnectivityHelper.LogHttpResponseHeaders(httpWebResponse.Headers, ref stringBuilder); httpWebResponse.Close(); } } stringBuilder.AppendLine(Strings.TestOutboundOauthLog); stringBuilder.AppendLine(Strings.ClientRequestId(value.ToString())); stringBuilder.AppendLine(oauthCredentials.Tracer.ToString()); stringBuilder.AppendLine(Strings.TestOAuthResponseDetails("Generic")); stringBuilder.AppendLine(Strings.ResponseMessage(s)); if (text != string.Empty) { stringBuilder.AppendLine(Strings.ExceptionHeader); stringBuilder.AppendLine(text); } diagnosticMessage = stringBuilder.ToString(); return(result); }
public static ResultType SendExchangeOAuthRequest(ADUser user, string orgDomain, Uri targetUri, out string diagnosticMessage, bool appOnly = false, bool useCachedToken = false, bool reloadConfig = false) { string domain = TestOAuthConnectivityHelper.GetDomain(user, orgDomain); if (domain == null) { diagnosticMessage = Strings.NullUserError; return(ResultType.Error); } ICredentials icredentials = TestOAuthConnectivityHelper.GetICredentials(false, user, domain); OAuthCredentials oauthCredentials = icredentials as OAuthCredentials; if (icredentials == null) { diagnosticMessage = Strings.NullUserError; return(ResultType.Error); } string value = "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\">\r\n <soap:Header>\r\n <t:RequestServerVersion Version=\"Exchange2012\"/>\r\n </soap:Header>\r\n <soap:Body>\r\n <GetFolder xmlns=\"http://schemas.microsoft.com/exchange/services/2006/messages\">\r\n <FolderShape>\r\n <t:BaseShape>IdOnly</t:BaseShape>\r\n </FolderShape>\r\n <FolderIds>\r\n <t:DistinguishedFolderId Id=\"inbox\"/>\r\n </FolderIds>\r\n </GetFolder>\r\n </soap:Body>\r\n </soap:Envelope>"; ValidationResultCollector resultCollector = new ValidationResultCollector(); LocalConfiguration localConfiguration = LocalConfiguration.Load(resultCollector); oauthCredentials.Tracer = new TestOAuthConnectivityHelper.TaskOauthOutboundTracer(); oauthCredentials.LocalConfiguration = localConfiguration; Guid value2 = Guid.NewGuid(); oauthCredentials.ClientRequestId = new Guid?(value2); HttpWebResponse httpWebResponse = null; ResultType result = ResultType.Success; string text = string.Empty; string s = string.Empty; StringBuilder stringBuilder = new StringBuilder(); string value3 = TestOAuthConnectivityHelper.CheckReloadConfig(reloadConfig); string value4 = TestOAuthConnectivityHelper.CheckUseCachedToken(useCachedToken); stringBuilder.AppendLine(value3); stringBuilder.AppendLine(value4); try { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri(targetUri.Scheme + "://" + targetUri.Host + "/ews/Exchange.asmx")); httpWebRequest.Method = "POST"; httpWebRequest.ContentType = "text/xml"; httpWebRequest.Headers.Add("X-ExCompId", "OauthPartnerProbe:"); httpWebRequest.Headers.Add("client-request-id", value2.ToString()); httpWebRequest.Headers.Add("request-id", value2.ToString()); httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer"); httpWebRequest.UserAgent = "AMProbe/OAUTH/Exchange"; httpWebRequest.Credentials = icredentials; StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()); streamWriter.Write(value); streamWriter.Close(); httpWebResponse = (httpWebRequest.GetResponse() as HttpWebResponse); if (httpWebResponse != null && httpWebResponse.StatusCode != HttpStatusCode.OK) { throw new Exception(Strings.HttpWebRequestFailure(httpWebResponse.StatusCode.ToString())); } using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream())) { s = streamReader.ReadToEnd(); } } catch (Exception ex) { text = ex.ToString(); result = ResultType.Error; } finally { if (httpWebResponse != null) { TestOAuthConnectivityHelper.LogHttpResponseHeaders(httpWebResponse.Headers, ref stringBuilder); httpWebResponse.Close(); } } stringBuilder.AppendLine(Strings.TestOutboundOauthLog); stringBuilder.AppendLine(Strings.ClientRequestId(value2.ToString())); stringBuilder.AppendLine(oauthCredentials.Tracer.ToString()); stringBuilder.AppendLine(Strings.TestOAuthResponseDetails("Exchange")); stringBuilder.AppendLine(Strings.ResponseMessage(s)); if (text != string.Empty) { stringBuilder.AppendLine(Strings.ExceptionHeader); stringBuilder.AppendLine(text); } diagnosticMessage = stringBuilder.ToString(); return(result); }
public static ResultType SendAutodiscoverOAuthRequest(ADUser user, string orgDomain, Uri targetUri, out string diagnosticMessage, bool appOnly = false, bool useCachedToken = false, bool reloadConfig = false) { string domain = TestOAuthConnectivityHelper.GetDomain(user, orgDomain); if (domain == null) { diagnosticMessage = Strings.NullUserError; return(ResultType.Error); } ICredentials icredentials = TestOAuthConnectivityHelper.GetICredentials(appOnly, user, domain); OAuthCredentials oauthCredentials = icredentials as OAuthCredentials; if (icredentials == null) { diagnosticMessage = Strings.NullUserError; return(ResultType.Error); } StringBuilder stringBuilder = new StringBuilder(); ValidationResultCollector resultCollector = new ValidationResultCollector(); LocalConfiguration localConfiguration = LocalConfiguration.Load(resultCollector); oauthCredentials.Tracer = new TestOAuthConnectivityHelper.TaskOauthOutboundTracer(); oauthCredentials.LocalConfiguration = localConfiguration; Guid value = Guid.NewGuid(); oauthCredentials.ClientRequestId = new Guid?(value); string value2 = TestOAuthConnectivityHelper.CheckReloadConfig(reloadConfig); string value3 = TestOAuthConnectivityHelper.CheckUseCachedToken(useCachedToken); stringBuilder.AppendLine(value2); stringBuilder.AppendLine(value3); AutodiscoverService autodiscoverService = new AutodiscoverService(4); autodiscoverService.Url = new Uri(targetUri.Scheme + "://" + targetUri.Host + "/autodiscover/autodiscover.svc"); autodiscoverService.TraceEnabled = true; autodiscoverService.Credentials = new OAuthCredentials(oauthCredentials); ResultType result = ResultType.Success; try { string text = (user == null) ? ("@" + domain) : user.PrimarySmtpAddress.ToString(); GetUserSettingsResponse userSettings = autodiscoverService.GetUserSettings(text, new UserSettingName[] { 58, 75 }); if (userSettings.ErrorCode != null && (userSettings.ErrorCode != 3 || !(text == "@" + domain))) { result = ResultType.Error; } } catch (Exception ex) { stringBuilder.AppendLine(ex.ToString()); result = ResultType.Error; } stringBuilder.AppendLine(Strings.TestOutboundOauthLog); stringBuilder.AppendLine(Strings.ClientRequestId(value.ToString())); stringBuilder.AppendLine(oauthCredentials.Tracer.ToString()); stringBuilder.AppendLine(Strings.TestOAuthResponseDetails("Exchange")); stringBuilder.AppendLine(Strings.TestOutboundOauthLog); stringBuilder.AppendLine(Strings.TestOAuthResponseDetails("Autodiscover")); stringBuilder.AppendLine(oauthCredentials.Tracer.ToString()); diagnosticMessage = stringBuilder.ToString(); return(result); }
/** * Actually post the image... finally. **/ private void Post_Click(object sender, EventArgs e) { // Check if we have credentials IsolatedStorageSettings storage = IsolatedStorageSettings.ApplicationSettings; // If we have no credentials, force the user to enter their info in account settings. if (!storage.Contains("userCredentials")) { NavigationService.Navigate(new Uri("/AccountSettingsPage.xaml", UriKind.Relative)); } else { // Get the credentials TumblrCredentials userCredentials = storage["userCredentials"] as TumblrCredentials; // We have credentials, do we have a photo? if (photo != null) { // Now here comes the POST! // Create a RestClient RestClient client = new RestClient(); client.Authority = MainPage.TUMBLR_AUTHORITY; client.HasElevatedPermissions = true; client.Path = MainPage.TUMBLR_POST_PATH; client.Method = Hammock.Web.WebMethod.Post; // Set the correct credentials on the client or request depending on auth method if (userCredentials.Type == TumblrCredentials.CredentialsType.OAuth) { OAuthCredentials oAuthCred = new OAuthCredentials(); oAuthCred.ConsumerKey = Common.OAUTH_CONSUMER_KEY; oAuthCred.ConsumerSecret = Common.OAUTH_CONSUMER_SECRET; oAuthCred.Token = userCredentials.OAuthToken; oAuthCred.TokenSecret = userCredentials.OAuthTokenSecret; oAuthCred.ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader; oAuthCred.SignatureMethod = OAuthSignatureMethod.HmacSha1; oAuthCred.Type = OAuthType.ProtectedResource; client.Credentials = oAuthCred; } else { client.AddField("email", userCredentials.Username); client.AddField("password", userCredentials.Password); } // Add metadata fields client.AddField("type", "photo"); //client.AddField("state", "draft"); // Debug line for testing client.AddField("send-to-twitter", "auto"); // Debug line because I'm paranoid // Add caption but check for an empty field if (!this.hasDefaultText) { client.AddField("caption", this.captionTextbox.Text); } client.AddFile("data", "upload.jpg", new MemoryStream(photo)); // Send the request of to la-la-land client.BeginRequest(new RestCallback(PostCompleted)); this.isPosting = true; // HACK: Well this is hacky... Dispatcher.BeginInvoke(() => ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false); Dispatcher.BeginInvoke(() => { this.postProgress.Visibility = System.Windows.Visibility.Visible; this.captionTextbox.IsEnabled = false; this.postProgress.Focus(); }); } else { Dispatcher.BeginInvoke(() => MessageBox.Show("Please Select a Photo.")); } } }
private void m_oaApi_RequestTokenReceived(object sender, bool bSucceeded, string sErrorMessage, OAuthCredentials oaCredentials) { if (bSucceeded) { m_oaCredentials = oaCredentials; txtUrl.Text = OAuthAPI.GetRequestURL(m_oaCredentials); ToggleLoadingAnimation(false); ToggleButtons(true); m_aaStatus = (AddAccountStatus)((int)m_aaStatus + 1); UpdateFromStatus(); } else { MessageBox.Show(sErrorMessage, "OAuth Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); m_aaStatus = AddAccountStatus.Pin; UpdateFromStatus(); ToggleButtons(true); ToggleLoadingAnimation(false); } }
public static async Task <OAuthCredentials> RefreshAccessToken(OAuthCredentials Credentials, string clientId, string clientSecret) { return(await RefreshAccessToken(Credentials.Refresh_token, clientId, clientSecret)); }
public StreamingAPI(OAuthCredentials oaCredentials) : base(oaCredentials) { }
public Account(OAuthCredentials oaCredentials) { m_oaCredentials = oaCredentials; Initialize(); }
/// <summary> /// Sends request to Twitter /// </summary> /// <param name="url">Request url</param> /// <param name="mapParams">Request parameters</param> /// <param name="method">Request method</param> /// <param name="callback">Method to be called when request finishes</param> public static void request(String url, Dictionary <String, String> mapParams, String method, Action <String, NetmeraException> callback) { if (twitter != null && twitter.isSessionValid()) { try { var credentials = new OAuthCredentials { Type = OAuthType.ProtectedResource, SignatureMethod = OAuthSignatureMethod.HmacSha1, ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, ConsumerKey = twitter.getConsumerKey(), ConsumerSecret = twitter.getConsumerSecret(), Token = twitter.getAccessToken(), TokenSecret = twitter.getSecretToken(), Version = "1.0", }; var request = new RestRequest(); request.Credentials = credentials; if (!String.IsNullOrEmpty(url)) { request.Path = url.Replace("http://", "https://").Replace(Twitter.ApiHost, ""); } if (!String.IsNullOrEmpty(method) && method.ToUpper().Trim() == "POST") { request.Method = WebMethod.Post; } if (mapParams != null && mapParams.Count != 0) { foreach (var key in mapParams.Keys) { request.AddParameter(key, mapParams[key]); } } var client = new RestClient { Authority = Twitter.ApiHost, HasElevatedPermissions = true }; client.BeginRequest(request, new RestCallback((req, resp, userstate) => { if (resp.StatusCode != HttpStatusCode.OK) { JObject json = JObject.Parse(resp.Content); if (json["error"] != null) { if (callback != null) { callback(null, new NetmeraException(NetmeraException.ErrorCode.EC_TW_ERROR, json.Value <String>("error"))); } } else { if (callback != null) { callback(null, new NetmeraException(NetmeraException.ErrorCode.EC_TW_ERROR, "Request error occured.")); } } } else { if (callback != null) { callback(resp.Content, null); } } })); } catch { if (callback != null) { callback(null, new NetmeraException(NetmeraException.ErrorCode.EC_TW_ERROR, "Request error occured.")); } } } else { if (callback != null) { callback(null, new NetmeraException(NetmeraException.ErrorCode.EC_TW_ERROR, "Must first login.")); } } }
public Account(string sAccessKey, string sAccessSecret, string sUsername, string sPassword) { m_oaCredentials = OAuthAPI.GetCredentials(sAccessKey, sAccessSecret, sUsername, sPassword); Initialize(); }
/// <summary> /// Gets the authorization request URL that a user should visit via their browser. If the request is being /// made via OAuth, the user will be given a pin that they will need to call OAuth() with. /// </summary> /// <returns></returns> public static string GetRequestURL(OAuthCredentials oaCredentials) { return(C_OAUTH_BASE_URL + C_AUTHORIZE_URL + "?oauth_token=" + oaCredentials.Token); }
public GoogleTokenValidator(OAuthCredentials credentials) { _credentials = credentials; }
public OAuthResponseObject(RestResponseHash rrhResponse, OAuthCredentials oaCredentials) { m_rrhResponse = rrhResponse; m_oaCredentials = oaCredentials; }
public AuthenicationCredentials CreateCredentials() { return(OAuthCredentials.CreateAutoCredentials(this.AccessToken)); }
public ITokenValidator Create(OAuthCredentials credentials) => credentials == null ? throw new ArgumentNullException(nameof(credentials)) : (ITokenValidator)Activator.CreateInstance(TokenValidatorTypeNames[_tokenProvider], credentials);
private ICredentials GetCredentials() { ADUser accessingADUser = this.callContext.AccessingADUser; return(OAuthCredentials.GetOAuthCredentialsForAppActAsToken(accessingADUser.OrganizationId, accessingADUser, null)); }
private string QuerySharePoint(OAuthCredentials oAuthCredential) { string text = string.Empty; if (oAuthCredential == null) { this.LogError("[GetInlineExploreSpContent.QuerySharePoint(OAuthCredentials oAuthCredential)]", "Credentials missing"); return(text); } if (string.IsNullOrEmpty(this.TargetUrl)) { this.LogError("[GetInlineExploreSpContent.QuerySharePoint(OAuthCredentials oAuthCredential)]", "TargetUrl missing"); return(text); } Guid value = Guid.NewGuid(); oAuthCredential.ClientRequestId = new Guid?(value); oAuthCredential.Tracer = new GetInlineExploreSpContentCommand.GetInlineExploreSpContentOauthOutboundTracer(); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(this.TargetUrl); httpWebRequest.Method = "GET"; httpWebRequest.ContentType = "text/xml"; httpWebRequest.UserAgent = "Exchange/15.00.0000.000/InlineExplore"; httpWebRequest.Headers.Add("client-request-id", value.ToString()); httpWebRequest.Headers.Add("return-client-request-id", "true"); httpWebRequest.Credentials = oAuthCredential; httpWebRequest.PreAuthenticate = true; httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer"); httpWebRequest.Timeout = 3000; try { using (HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse) { if (httpWebResponse != null && httpWebResponse.StatusCode != HttpStatusCode.OK) { throw new Exception(string.Format("Http status code is {0}", httpWebResponse.StatusCode)); } using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream())) { text = streamReader.ReadToEnd(); } } } catch (OAuthTokenRequestFailedException ex) { this.LogError("[GetInlineExploreSpContent.QuerySharePoint(OAuthCredentials oAuthCredential)]:OAuthException", oAuthCredential.Tracer.ToString() + ex.ToString(), value.ToString()); } catch (WebException ex2) { this.LogError("[GetInlineExploreSpContent.QuerySharePoint(OAuthCredentials oAuthCredential)]:WebException", ex2.ToString(), value.ToString()); } catch (Exception ex3) { this.LogError("[GetInlineExploreSpContent.QuerySharePoint(OAuthCredentials oAuthCredential)]:Exception", ex3.ToString(), value.ToString()); } if (string.IsNullOrEmpty(text)) { this.LogError("[GetInlineExploreSpContent.QuerySharePoint(OAuthCredentials oAuthCredential)]:No content in response", "Expected response from SharePoint", value.ToString()); } return(text); }
public async Task <IActionResult> AddTwitterAccount(bool follow) { int count = 0; Domain.Socioboard.Models.User user = HttpContext.Session.GetObjectFromJson <Domain.Socioboard.Models.User>("User"); string profileCount = await ProfilesHelper.GetUserProfileCount(user.Id, _appSettings, _logger); try { count = Convert.ToInt32(profileCount); } catch (Exception ex) { TempData["Error"] = "Error while getting profile count."; return(RedirectToAction("Index", "Home")); } int MaxCount = Domain.Socioboard.Helpers.SBHelper.GetMaxProfileCount(user.AccountType); if (count >= MaxCount) { TempData["Error"] = "Max profile Count reached."; return(RedirectToAction("Index", "Home")); } else { if (follow) { HttpContext.Session.SetObjectAsJson("Twitter", "Twitter_Account_Follow"); } else { HttpContext.Session.SetObjectAsJson("Twitter", "Twitter_Account"); } OAuthCredentials credentials = new OAuthCredentials() { Type = OAuthType.RequestToken, SignatureMethod = OAuthSignatureMethod.HmacSha1, ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, ConsumerKey = _appSettings.twitterConsumerKey, ConsumerSecret = _appSettings.twitterConsumerScreatKey, CallbackUrl = _appSettings.twitterRedirectionUrl }; // Use Hammock to create a rest client var client = new RestClient { Authority = "https://api.twitter.com/oauth", Credentials = credentials, }; // Use Hammock to create a request var request = new RestRequest { Path = "request_token" }; // Get the response from the request var response = client.Request(request); var collection = HttpUtility.ParseQueryString(response.Content); //string str = collection[1].ToString(); //HttpContext.Current.Session["requestSecret"] = collection[1]; string rest = "https://api.twitter.com/oauth/authorize?oauth_token=" + collection[0]; HttpContext.Session.SetObjectAsJson("requestSecret", collection[1]); return(Redirect(rest)); } }
//void fb_PostCompleted(object sender, FacebookApiEventArgs e) //{ // if (e.Error != null) // { // Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message)); // return; // } // else // { // Dispatcher.BeginInvoke(() => // { // progbar1.IsIndeterminate = false; // progbar1.Visibility = Visibility.Collapsed; // MessageBox.Show("Successfully shared on Facebook"); // //if (NavigationService.CanGoBack) // // NavigationService.GoBack(); // }); // } //} public void ShareOnTwitter() { OAuthCredentials credentials = new OAuthCredentials(); credentials.Type = OAuthType.ProtectedResource; credentials.SignatureMethod = OAuthSignatureMethod.HmacSha1; credentials.ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader; credentials.ConsumerKey = TwitterSettings.ConsumerKey; credentials.ConsumerSecret = TwitterSettings.ConsumerKeySecret; credentials.Token = tokenx; credentials.TokenSecret = tokensecx; credentials.Version = "1.0"; //credentials.ClientUsername = ""; //credentials.CallbackUrl = "www.google.com"; //var service = new TwitterService(TwitterSettings.ConsumerKey, TwitterSettings.ConsumerKeySecret); //service.AuthenticateWith(tokenx, tokensecx); //var resized = img.Resize(img.PixelWidth / 4, img.PixelHeight / 4, WriteableBitmapExtensions.Interpolation.Bilinear); //var fileStream = new MemoryStream(); //resized.SaveJpeg(fileStream, resized.PixelWidth, resized.PixelHeight, 100, 100); //fileStream.Seek(0, SeekOrigin.Begin); //SendTweetWithMediaOptions msgMedia = new SendTweetWithMediaOptions(); //msgMedia.Status = photo_text.Text; //Dictionary<string, Stream> imageDict = new Dictionary<string, Stream> { { fileName, fileStream } }; ////imageDict.Add(imagePath, imageStream); //msgMedia.Images = imageDict; ////status = service.SendTweetWithMedia(new SendTweetWithMediaOptions() { Status = readerMsg.Message, Images = imageDict }); //service.SendTweetWithMedia(msgMedia, tweetResponse); //other method RestClient _client = new RestClient { Authority = "https://api.twitter.com", HasElevatedPermissions = true, }; var twitterRequest = new RestRequest { Credentials = credentials, Path = "/1.1/statuses/update_with_media.json", Method = WebMethod.Post }; //twitterRequest.AddHeader("content-type", "application/x-www-form-urlencoded"); //twitterRequest.AddHeader("content-type", "multipart/form-data"); //twitterRequest.AddField("consumer_token", TwitterSettings.ConsumerKey); //twitterRequest.AddField("consumer_secret", TwitterSettings.ConsumerKeySecret); //twitterRequest.AddField("oauth_token", tokenx); //twitterRequest.AddField("oauth_secret", tokensecx); var resized = img.Resize(img.PixelWidth / 4, img.PixelHeight / 4, WriteableBitmapExtensions.Interpolation.Bilinear); var fileStream = new MemoryStream(); resized.SaveJpeg(fileStream, resized.PixelWidth, resized.PixelHeight, 100, 100); fileStream.Seek(0, SeekOrigin.Begin); //twitterRequest.AddParameter("status", photo_text.Text); twitterRequest.AddField("status", photo_text.Text); twitterRequest.AddFile("media[]", "test", fileStream, "image/jpeg"); _client.BeginRequest(twitterRequest, NewTweetCompleted); // another method // var resized = img.Resize(img.PixelWidth / 4, img.PixelHeight / 4, WriteableBitmapExtensions.Interpolation.Bilinear); // var fileStream = new MemoryStream(); // resized.SaveJpeg(fileStream, resized.PixelWidth, resized.PixelHeight, 100, 100); // fileStream.Seek(0, SeekOrigin.Begin); // string fileUploadUrl = "http://api.twitter.com/1.1/statuses/update_with_media.json"; // HttpClientHandler handler = new HttpClientHandler(); //// handler.Credentials = new NetworkCredential("username", "password"); // handler.Credentials = new NetworkCredential(TwitterSettings.ConsumerKey, TwitterSettings.ConsumerKeySecret); // HttpClient client = new HttpClient(handler); // fileStream.Position = 0; // MultipartFormDataContent content = new MultipartFormDataContent(); // content.Add(new StreamContent(fileStream), "media[]", fileName); // await client.PostAsync(fileUploadUrl, content) // .ContinueWith((postTask) => // { // postTask.Result.EnsureSuccessStatusCode(); // }); }
/// <summary> /// Authenticates the application using OAuth with PIN code verification /// </summary> public void Authenticate() { if (Authenticated) { return; } // POST consumer_key and consumer_secret to obtain request token OAuthCredentials credential = new OAuthCredentials() { Type = OAuthType.RequestToken, SignatureMethod = OAuthSignatureMethod.HmacSha1, ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, ConsumerKey = ConsumerKey, ConsumerSecret = ConsumerSecret }; RestClient client = new RestClient() { Authority = "https://api.twitter.com/oauth", Credentials = credential }; var request = new RestRequest { Path = "/request_token", Method = WebMethod.Post }; RestResponse response = client.Request(request); var collection = System.Web.HttpUtility.ParseQueryString(response.Content); string requestToken = collection["oauth_token"]; string requestTokenSecret = collection["oauth_token_secret"]; // Obtain the PIN code Process.Start("http://api.twitter.com/oauth/authorize?oauth_token=" + requestToken); string code = null; OnRequestAuthenticationResponse(ref code); // Exchange Pin code for Access token // POST consumer_key and consumer_secret to obtain request token credential = new OAuthCredentials() { Type = OAuthType.AccessToken, SignatureMethod = OAuthSignatureMethod.HmacSha1, ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, ConsumerKey = ConsumerKey, ConsumerSecret = ConsumerSecret, Token = requestToken, TokenSecret = requestTokenSecret, Verifier = code }; client = new RestClient() { Authority = "https://api.twitter.com/oauth", Credentials = credential }; request = new RestRequest { Path = "/access_token", Method = WebMethod.Post }; response = client.Request(request); collection = HttpUtility.ParseQueryString(response.Content); AccessToken = collection["oauth_token"]; AccessTokenSecret = collection["oauth_token_secret"]; this._credentials = new OAuthCredentials { Type = OAuthType.ProtectedResource, Token = AccessToken, TokenSecret = AccessTokenSecret, ConsumerKey = ConsumerKey, ConsumerSecret = ConsumerSecret }; }
public void makeRecursiveApiCallTillLastPageOfApiResponse(Hammock.RestRequest request, OAuthCredentials credentials, Hammock.RestClient client) { Hammock.RestResponse response = client.Request(request); Fleet fleet = Deserialise <Fleet>(response.ContentStream); printFirstEquipmentDetailsFromEachPage(fleet); List <Links> links = fleet.Links; for (int i = 0; i < links.Count; i++) { if (links[i].Rel.Equals("next")) { request.Path = links[i].Href; makeRecursiveApiCallTillLastPageOfApiResponse(request, credentials, client); } } }
protected override void InternalProcessRecord() { ValidationResultCollector validationResultCollector = new ValidationResultCollector(); LocalConfiguration localConfiguration = LocalConfiguration.Load(validationResultCollector); foreach (ValidationResultNode sendToPipeline in validationResultCollector.Results) { base.WriteObject(sendToPipeline); } SharePointException ex = null; Uri uri = this.SharePointUrl ?? this.tmADObject.SharePointUrl; OAuthCredentials oauthCredentials = null; try { using (ClientContext clientContext = new ClientContext(uri)) { bool flag = false; ICredentials credentialAndConfigureClientContext = TeamMailboxHelper.GetCredentialAndConfigureClientContext(this.requestor, (this.requestor != null) ? this.requestor.OrganizationId : base.CurrentOrganizationId, clientContext, this.UseAppTokenOnly, out flag); if (!flag) { base.WriteError(new InvalidOperationException(Strings.OauthIsTurnedOff), ErrorCategory.InvalidOperation, null); } oauthCredentials = (credentialAndConfigureClientContext as OAuthCredentials); oauthCredentials.Tracer = new TestSiteMailbox.TaskOauthOutboundTracer(); oauthCredentials.LocalConfiguration = localConfiguration; Web web = clientContext.Web; clientContext.Load <Web>(web, new Expression <Func <Web, object> > [0]); clientContext.ExecuteQuery(); } } catch (ClientRequestException e) { ex = new SharePointException(uri.AbsoluteUri, e); } catch (ServerException e2) { ex = new SharePointException(uri.AbsoluteUri, e2); } catch (IOException ex2) { ex = new SharePointException(uri.AbsoluteUri, new LocalizedString(ex2.Message)); } catch (WebException e3) { ex = new SharePointException(uri.AbsoluteUri, e3, true); } if (ex != null) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(Strings.TestTeamMailboxOutboundOauthLog); stringBuilder.AppendLine(oauthCredentials.Tracer.ToString()); stringBuilder.AppendLine(Strings.TestTeamMailboxSharePointResponseDetails); stringBuilder.AppendLine(ex.DiagnosticInfo); ValidationResultNode sendToPipeline2 = new ValidationResultNode(Strings.TestTeamMailboxSharepointCallUnderOauthTask, new LocalizedString(stringBuilder.ToString()), ResultType.Error); base.WriteObject(sendToPipeline2); return; } StringBuilder stringBuilder2 = new StringBuilder(); stringBuilder2.AppendLine(Strings.TestTeamMailboxSharepointCallUnderOauthSuccess(uri.AbsoluteUri)); stringBuilder2.AppendLine(Strings.TestTeamMailboxOutboundOauthLog); stringBuilder2.AppendLine(oauthCredentials.Tracer.ToString()); ValidationResultNode sendToPipeline3 = new ValidationResultNode(Strings.TestTeamMailboxSharepointCallUnderOauthTask, new LocalizedString(stringBuilder2.ToString()), ResultType.Success); base.WriteObject(sendToPipeline3); }