/// <summary> /// Creates a web request prepared with OAuth authorization /// that may be further tailored by adding parameters by the caller. /// </summary> /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param> /// <param name="accessToken">The access token that permits access to the protected resource.</param> /// <returns>The initialized WebRequest object.</returns> public WebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint endpoint, string accessToken) { IDirectedProtocolMessage message = this.CreateAuthorizingMessage(endpoint, accessToken); HttpWebRequest wr = this.OAuthChannel.InitializeRequest(message); return(wr); }
/// <summary> /// Analyzes an incoming request message payload to discover what kind of /// message is embedded in it and returns the type, or null if no match is found. /// </summary> /// <param name="recipient">The intended or actual recipient of the request message.</param> /// <param name="fields">The name/value pairs that make up the message payload.</param> /// <returns> /// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can /// deserialize to. Null if the request isn't recognized as a valid protocol message. /// </returns> public IDirectedProtocolMessage GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary <string, string> fields) { RequestBase message = null; // Discern the OpenID version of the message. Protocol protocol = Protocol.V11; string ns; if (fields.TryGetValue(Protocol.V20.openid.ns, out ns)) { ErrorUtilities.VerifyProtocol(string.Equals(ns, Protocol.OpenId2Namespace, StringComparison.Ordinal), MessagingStrings.UnexpectedMessagePartValue, Protocol.V20.openid.ns, ns); protocol = Protocol.V20; } string mode; if (fields.TryGetValue(protocol.openid.mode, out mode)) { if (string.Equals(mode, protocol.Args.Mode.associate)) { if (fields.ContainsKey(protocol.openid.dh_consumer_public)) { message = new AssociateDiffieHellmanProviderRequest(protocol.Version, recipient.Location); } else { message = new AssociateUnencryptedProviderRequest(protocol.Version, recipient.Location); } } else if (string.Equals(mode, protocol.Args.Mode.checkid_setup) || string.Equals(mode, protocol.Args.Mode.checkid_immediate)) { AuthenticationRequestMode authMode = string.Equals(mode, protocol.Args.Mode.checkid_immediate) ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup; if (fields.ContainsKey(protocol.openid.identity)) { message = new CheckIdRequest(protocol.Version, recipient.Location, authMode); } else { ErrorUtilities.VerifyProtocol(!fields.ContainsKey(protocol.openid.claimed_id), OpenIdStrings.IdentityAndClaimedIdentifierMustBeBothPresentOrAbsent); message = new SignedResponseRequest(protocol.Version, recipient.Location, authMode); } } else if (string.Equals(mode, protocol.Args.Mode.check_authentication)) { message = new CheckAuthenticationRequest(protocol.Version, recipient.Location); } else { ErrorUtilities.ThrowProtocol(MessagingStrings.UnexpectedMessagePartValue, protocol.openid.mode, mode); } } if (message != null) { message.SetAsIncoming(); } return(message); }
// * Redeem upload token // Implements http://www.23developer.com/api/photo-redeem-upload-token public bool RedeemUploadToken(string filename, string fileContentType, System.IO.Stream filestream, string uploadToken) { // Verify required parameters if (filestream == null) { return(false); } // Ensure that only relative filenames are sent int relativeFilenameSplit = filename.LastIndexOf('\\'); string relativeFilename = (relativeFilenameSplit == -1 ? filename : filename.Substring(relativeFilenameSplit + 1)); // Build request URL List <MultipartPostPart> data = new List <MultipartPostPart> { MultipartPostPart.CreateFormFilePart("file", relativeFilename, fileContentType, filestream), MultipartPostPart.CreateFormPart("upload_token", uploadToken) }; // Do the request MessageReceivingEndpoint requestMessage = new MessageReceivingEndpoint(_provider.GetRequestUrl("/api/photo/redeem-upload-token", null), HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); XPathNavigator responseMessage = _provider.DoRequest(requestMessage, data); if (responseMessage == null) { return(false); } // If nothing pops up, we'll return null return(true); }
private XDocument SendPCORequest(XDocument data, MessageReceivingEndpoint endpoint) { string stringData = data.Declaration.ToString() + data.ToString(SaveOptions.DisableFormatting); byte[] postData = ASCIIEncoding.ASCII.GetBytes(stringData); HttpWebRequest request = _pcoConsumer.PrepareAuthorizedRequest(endpoint, _accessToken); request.Proxy.Credentials = CredentialCache.DefaultCredentials; request.ContentType = "application/xml"; request.ContentLength = postData.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(postData, 0, postData.Length); requestStream.Close(); try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); return(GetResponse(response.GetResponseStream(), response.ContentType, response.StatusCode)); } catch (WebException webException) { SaveResponse(webException.Response.GetResponseStream()); throw new Exception(webException.Message + " - " + HTMLResponse); } }
private async Task <T> CallServiceAsync <T>(Func <DataApiClient, T> predicate) { DataApiClient client = new DataApiClient(); var serviceEndpoint = new MessageReceivingEndpoint(client.Endpoint.Address.Uri, HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest); var accessToken = (AccessToken)(Session["WcfAccessToken"] ?? default(AccessToken)); if (accessToken.Token == null) { throw new InvalidOperationException("No access token!"); } var httpRequest = new HttpRequestMessage(HttpMethod.Post, client.Endpoint.Address.Uri); var consumer = this.CreateConsumer(); using (var handler = consumer.CreateMessageHandler(accessToken)) { handler.ApplyAuthorization(httpRequest); } HttpRequestMessageProperty httpDetails = new HttpRequestMessageProperty(); httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers.Authorization.ToString(); using (OperationContextScope scope = new OperationContextScope(client.InnerChannel)) { OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails; return(predicate(client)); } }
// * Update album // Implements http://www.23developer.com/api/album-update public bool Update(int albumId, string title, string description = "", bool hide = false) { // Verify required parameters if (String.IsNullOrEmpty(title)) { return(false); } // Build request URL List <string> requestUrlParameters = new List <string>(); requestUrlParameters.Add("album_id=" + albumId); requestUrlParameters.Add("title=" + HttpUtility.UrlEncode(title)); if (!String.IsNullOrEmpty(description)) { requestUrlParameters.Add("description=" + HttpUtility.UrlEncode(description)); } if (hide) { requestUrlParameters.Add("hide_p=1"); } // Do the request MessageReceivingEndpoint requestMessage = new MessageReceivingEndpoint(_provider.GetRequestUrl("/api/album/update", requestUrlParameters), HttpDeliveryMethods.GetRequest); XPathNavigator responseMessage = _provider.DoRequest(requestMessage); if (responseMessage == null) { return(false); } // If nothing pops up, we'll return true return(true); }
private WebConsumer CreateConsumer() { String authHandler = authHandleTextBox.Text; string consumerKey = consumerKeyTextBox.Text; string consumerSecret = consumerSecretTextBox.Text; Session["authHandler"] = authHandler; var tokenManager = Session["WcfTokenManager"] as InMemoryTokenManager; if (tokenManager == null) { tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); Session["WcfTokenManager"] = tokenManager; } MessageReceivingEndpoint oauthEndpoint = new MessageReceivingEndpoint( new Uri(authHandler), HttpDeliveryMethods.PostRequest); WebConsumer consumer = new WebConsumer( new ServiceProviderDescription { RequestTokenEndpoint = oauthEndpoint, UserAuthorizationEndpoint = oauthEndpoint, AccessTokenEndpoint = oauthEndpoint, TamperProtectionElements = new DotNetOpenAuth.Messaging.ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement(), }, }, tokenManager); return(consumer); }
// * Replace photo // Implements http://www.23developer.com/api/photo-replace /// <summary> /// Replace a photo thumbnail given an id /// </summary> /// <param name="photoId">Id of photo</param> /// <param name="filename">The original filename</param> /// <param name="fileContentType">The meta content type of the file</param> /// <param name="filestream">An input stream for reading the file</param> /// <returns></returns> public bool Replace(int photoId, string filename, string fileContentType, System.IO.Stream filestream) { // Build request URL List <string> requestUrlParameters = new List <string>(); // Ensure that only relative filenames are sent int relativeFilenameSplit = filename.LastIndexOf('\\'); string relativeFilename = (relativeFilenameSplit == -1 ? filename : filename.Substring(relativeFilenameSplit + 1)); // Do the request MessageReceivingEndpoint requestMessage = new MessageReceivingEndpoint(_provider.GetRequestUrl("/api/photo/replace", requestUrlParameters), HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); List <MultipartPostPart> data = new List <MultipartPostPart> { MultipartPostPart.CreateFormPart("photo_id", photoId.ToString()), MultipartPostPart.CreateFormFilePart("file", relativeFilename, fileContentType, filestream) }; XPathNavigator responseMessage = _provider.DoRequest(requestMessage, data); if (responseMessage == null) { return(false); } // If nothing pops up, we'll return true return(true); }
public void VerifyAuthenticationFailsIfAccessTokenIsInvalid() { // Arrange var endpoint = new MessageReceivingEndpoint("http://live.com/path/?a=b", HttpDeliveryMethods.GetRequest); var request = new AuthorizedTokenRequest(endpoint, new Version("1.0")); var response = new AuthorizedTokenResponse(request) { AccessToken = "invalid token" }; var webWorker = new Mock <IOAuthWebWorker>(MockBehavior.Strict); webWorker.Setup(w => w.ProcessUserAuthorization()).Returns(response).Verifiable(); var client = new MockOAuthClient(webWorker.Object); var context = new Mock <HttpContextBase>(); // Act AuthenticationResult result = client.VerifyAuthentication(context.Object); // Assert webWorker.Verify(); Assert.False(result.IsSuccessful); }
protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) { string accessToken = response.AccessToken; string userId = response.ExtraData["user_id"]; string userName = response.ExtraData["screen_name"]; var profileRequestUrl = new Uri("https://api.twitter.com/1/users/show.xml?user_id=" + MessagingUtilities.EscapeUriDataStringRfc3986(userId)); var profileEndpoint = new MessageReceivingEndpoint(profileRequestUrl, HttpDeliveryMethods.GetRequest); HttpWebRequest request = this.WebWorker.PrepareAuthorizedRequest(profileEndpoint, accessToken); var extraData = new Dictionary <string, string>(); extraData.Add("accesstoken", accessToken); try { using (WebResponse profileResponse = request.GetResponse()) { using (Stream responseStream = profileResponse.GetResponseStream()) { XDocument document = LoadXDocumentFromStream(responseStream); extraData.AddDataIfNotEmpty(document, "name"); extraData.AddDataIfNotEmpty(document, "location"); extraData.AddDataIfNotEmpty(document, "description"); extraData.AddDataIfNotEmpty(document, "url"); } } } catch (Exception) { // At this point, the authentication is already successful. // Here we are just trying to get additional data if we can. // If it fails, no problem. } return(new AuthenticationResult( isSuccessful: true, provider: this.ProviderName, providerUserId: userId, userName: userName, extraData: extraData)); }
public XDocument GetPerson(string pcoId) { if (pcoId != "-1") { MessageReceivingEndpoint GetPersonEndpoint = new MessageReceivingEndpoint( string.Format("https://www.planningcenteronline.com/people/{0}.xml", pcoId), HttpDeliveryMethods.GetRequest); HttpWebRequest request = _pcoConsumer.PrepareAuthorizedRequest(GetPersonEndpoint, _accessToken); request.Proxy.Credentials = CredentialCache.DefaultCredentials; try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); return(GetResponse(response.GetResponseStream(), response.ContentType, response.StatusCode)); } catch (WebException webException) { if (webException.Response.Headers["Status"].StartsWith("404")) { return(null); } else { SaveResponse(webException.Response.GetResponseStream()); throw new Exception(webException.Message + " - " + HTMLResponse); } } } else { return(null); } }
/// <summary> /// Creates a web request prepared with OAuth authorization /// that may be further tailored by adding parameters by the caller. /// </summary> /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param> /// <param name="accessToken">The access token that permits access to the protected resource.</param> /// <returns>The initialized WebRequest object.</returns> /// <exception cref="WebException">Thrown if the request fails for any reason after it is sent to the Service Provider.</exception> public IncomingWebResponse PrepareAuthorizedRequestAndSend(MessageReceivingEndpoint endpoint, string accessToken) { IDirectedProtocolMessage message = this.CreateAuthorizingMessage(endpoint, accessToken); HttpWebRequest wr = this.OAuthChannel.InitializeRequest(message); return(this.Channel.WebRequestHandler.GetResponse(wr)); }
/// <summary> /// Creates a web request prepared with OAuth authorization /// that may be further tailored by adding parameters by the caller. /// </summary> /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param> /// <param name="accessToken">The access token that permits access to the protected resource.</param> /// <returns>The initialized WebRequest object.</returns> public HttpWebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint endpoint, string accessToken) { Contract.Requires <ArgumentNullException>(endpoint != null); Contract.Requires <ArgumentNullException>(!String.IsNullOrEmpty(accessToken)); return(this.PrepareAuthorizedRequest(endpoint, accessToken, EmptyDictionary <string, string> .Instance)); }
static void Main(string[] args) { var providerDesc = new ServiceProviderDescription() { RequestTokenEndpoint = new MessageReceivingEndpoint("http://localhost:8008/noop", HttpDeliveryMethods.PostRequest), AccessTokenEndpoint = new MessageReceivingEndpoint("http://localhost:8008/noop", HttpDeliveryMethods.PostRequest), UserAuthorizationEndpoint = new MessageReceivingEndpoint("http://localhost:8008/noop", HttpDeliveryMethods.PostRequest), ProtocolVersion = ProtocolVersion.V10a, TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() } }; var consumerKey = "dotnet-test-key"; var consumerSecret = File.ReadAllText("..\\..\\keys\\8008\\8080\\" + consumerKey); var zeroLeggedWebConsumer = new DotNetOpenAuth.OAuth.WebConsumer(providerDesc, new ZeroLeggedTokenManager(consumerKey, consumerSecret)); var endpoint = new MessageReceivingEndpoint("http://localhost:8008/job?query=parameters&also=good", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest); var httpRequest = zeroLeggedWebConsumer.PrepareAuthorizedRequest(endpoint, "DUMMY", new Dictionary <String, String>() { { "are", "post" }, { "parameters", "handled" }, }); var response = httpRequest.GetResponse(); var responseContent = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd(); Console.Out.WriteLine(responseContent); }
/// <summary> /// Creates a web request prepared with OAuth authorization /// that may be further tailored by adding parameters by the caller. /// </summary> /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param> /// <param name="accessToken">The access token that permits access to the protected resource.</param> /// <returns>The initialized WebRequest object.</returns> public HttpWebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint endpoint, string accessToken) { Requires.NotNull(endpoint, "endpoint"); Requires.NotNullOrEmpty(accessToken, "accessToken"); return(this.PrepareAuthorizedRequest(endpoint, accessToken, EmptyDictionary <string, string> .Instance)); }
public async Task VerifyAuthenticationSucceeds() { // Arrange var endpoint = new MessageReceivingEndpoint("http://live.com/path/?a=b", HttpDeliveryMethods.GetRequest); var request = new AuthorizedTokenRequest(endpoint, new Version("1.0")); var webWorker = new Mock <IOAuthWebWorker>(MockBehavior.Strict); webWorker .Setup(w => w.ProcessUserAuthorizationAsync(It.IsAny <HttpContextBase>(), CancellationToken.None)) .Returns(Task.FromResult(new AccessTokenResponse("ok", "secret", new NameValueCollection()))).Verifiable(); var client = new MockOAuthClient(webWorker.Object); var context = new Mock <HttpContextBase>(); // Act AuthenticationResult result = await client.VerifyAuthenticationAsync(context.Object); // Assert webWorker.Verify(); Assert.True(result.IsSuccessful); Assert.AreEqual("mockoauth", result.Provider); Assert.AreEqual("12345", result.ProviderUserId); Assert.AreEqual("super", result.UserName); Assert.IsNotNull(result.ExtraData); Assert.AreEqual("ok", result.ExtraData["accesstoken"]); }
internal AccessProtectedResourceRequest CreateResourceRequest(MessageReceivingEndpoint endpoint) { Contract.Requires(endpoint != null); var message = new AccessProtectedResourceRequest(endpoint, Protocol.V10.Version); return(message); }
public void VerifyAuthenticationSucceeds() { // Arrange var endpoint = new MessageReceivingEndpoint("http://live.com/path/?a=b", HttpDeliveryMethods.GetRequest); var request = new AuthorizedTokenRequest(endpoint, new Version("1.0")); var response = new AuthorizedTokenResponse(request) { AccessToken = "ok" }; var webWorker = new Mock <IOAuthWebWorker>(MockBehavior.Strict); webWorker.Setup(w => w.ProcessUserAuthorization()).Returns(response).Verifiable(); var client = new MockOAuthClient(webWorker.Object); var context = new Mock <HttpContextBase>(); // Act AuthenticationResult result = client.VerifyAuthentication(context.Object); // Assert webWorker.Verify(); Assert.True(result.IsSuccessful); Assert.AreEqual("mockoauth", result.Provider); Assert.AreEqual("12345", result.ProviderUserId); Assert.AreEqual("super", result.UserName); Assert.IsNotNull(result.ExtraData); Assert.IsTrue(result.ExtraData.ContainsKey("accesstoken")); Assert.AreEqual("ok", result.ExtraData["accesstoken"]); }
public Newtonsoft.Json.Linq.JArray Tweets() { var cache = System.Web.HttpContext.Current.Cache; JArray tweets = (JArray)cache["Tweets"]; if (tweets == null) { var token = Get().ApplicationAuthorizationKey; try { var consumer = new DotNetOpenAuth.OAuth.WebConsumer(ServiceProviderDescription(), new LongTermTokenProvider()); var endpoint = new MessageReceivingEndpoint("https://api.twitter.com/1.1/statuses/home_timeline.json", HttpDeliveryMethods.GetRequest); var request = consumer.PrepareAuthorizedRequest(endpoint, token); var response = request.GetResponse(); var data = (new StreamReader(response.GetResponseStream())).ReadToEnd(); tweets = JArray.Parse(data); cache.Insert("Tweets", tweets, null, DateTime.Now.AddMinutes(5), TimeSpan.Zero); } catch (Exception ex) { tweets = new JArray(); } } return(tweets); }
/// <summary> /// Initializes the <see cref="serviceProvider"/> field if it has not yet been initialized. /// </summary> private static void EnsureInitialized() { if (serviceProvider == null) { lock (initializerLock) { if (serviceDescription == null) { var postEndpoint = new MessageReceivingEndpoint(new Uri(Utilities.ApplicationRoot, "OAuth.ashx"), HttpDeliveryMethods.PostRequest); var getEndpoint = new MessageReceivingEndpoint(postEndpoint.Location, HttpDeliveryMethods.GetRequest); serviceDescription = new ServiceProviderDescription { TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, RequestTokenEndpoint = postEndpoint, AccessTokenEndpoint = postEndpoint, UserAuthorizationEndpoint = getEndpoint, }; } if (tokenManager == null) { tokenManager = new OAuthServiceProviderTokenManager(); } if (serviceProvider == null) { serviceProvider = new ServiceProvider(serviceDescription, tokenManager); } } } }
/// <summary> /// Analyzes an incoming request message payload to discover what kind of /// message is embedded in it and returns the type, or null if no match is found. /// </summary> /// <param name="recipient">The intended or actual recipient of the request message.</param> /// <param name="fields">The name/value pairs that make up the message payload.</param> /// <returns> /// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can /// deserialize to. Null if the request isn't recognized as a valid protocol message. /// </returns> /// <remarks> /// The request messages are: /// UnauthorizedTokenRequest /// AuthorizedTokenRequest /// UserAuthorizationRequest /// AccessProtectedResourceRequest /// </remarks> public virtual IDirectedProtocolMessage GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary <string, string> fields) { MessageBase message = null; Protocol protocol = Protocol.V10; // default to assuming the less-secure 1.0 instead of 1.0a until we prove otherwise. string token; fields.TryGetValue("oauth_token", out token); try { if (fields.ContainsKey("oauth_consumer_key") && !fields.ContainsKey("oauth_token")) { protocol = fields.ContainsKey("oauth_callback") ? Protocol.V10a : Protocol.V10; message = new UnauthorizedTokenRequest(recipient, protocol.Version); } else if (fields.ContainsKey("oauth_consumer_key") && fields.ContainsKey("oauth_token")) { // Discern between RequestAccessToken and AccessProtectedResources, // which have all the same parameters, by figuring out what type of token // is in the token parameter. bool tokenTypeIsAccessToken = this.tokenManager.GetTokenType(token) == TokenType.AccessToken; if (tokenTypeIsAccessToken) { message = (MessageBase) new AccessProtectedResourceRequest(recipient, protocol.Version); } else { // Discern between 1.0 and 1.0a requests by checking on the consumer version we stored // when the consumer first requested an unauthorized token. protocol = Protocol.Lookup(this.tokenManager.GetRequestToken(token).ConsumerVersion); message = new AuthorizedTokenRequest(recipient, protocol.Version); } } else { // fail over to the message with no required fields at all. if (token != null) { protocol = Protocol.Lookup(this.tokenManager.GetRequestToken(token).ConsumerVersion); } // If a callback parameter is included, that suggests either the consumer // is following OAuth 1.0 instead of 1.0a, or that a hijacker is trying // to attack. Either way, if the consumer started out as a 1.0a, keep it // that way, and we'll just ignore the oauth_callback included in this message // by virtue of the UserAuthorizationRequest message not including it in its // 1.0a payload. message = new UserAuthorizationRequest(recipient, protocol.Version); } if (message != null) { message.SetAsIncoming(); } return(message); } catch (KeyNotFoundException ex) { throw ErrorUtilities.Wrap(ex, OAuthStrings.TokenNotFound); } }
private async Task <Tuple <T, Dictionary <string, TE> > > GetRequestWithExpansions <T, TE>(string baseAddress, string endpoint) { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(baseAddress); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (LoginType == LoginType.Anonymous) { endpoint = string.Format("{0}{2}APIKey={1}", endpoint, smugmugTokenManager.ConsumerKey, endpoint.Contains('?') ? "&" : "?"); } else if (LoginType == LoginType.OAuth) { smugmugConsumer = new DesktopConsumer(smugmugServiceDescription, smugmugTokenManager); HttpDeliveryMethods resourceHttpMethod = HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest; var resourceEndpoint = new MessageReceivingEndpoint(baseAddress + endpoint, resourceHttpMethod); var httpRequest = smugmugConsumer.PrepareAuthorizedRequest(resourceEndpoint, smugmugTokenManager.AccessToken); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", httpRequest.Headers["Authorization"].Substring(6)); } else { throw new NotSupportedException(string.Format("LoginType {0} is unsupported", LoginType)); } HttpResponseMessage httpResponse = client.GetAsync(endpoint).Result; System.Diagnostics.Trace.WriteLine(string.Format("GET {0}", httpResponse.RequestMessage.RequestUri)); httpResponse.EnsureSuccessStatusCode(); GetResponseWithExpansionStub <T, TE> contentResponse = await httpResponse.Content.ReadAsAsync <GetResponseWithExpansionStub <T, TE> >(); System.Diagnostics.Trace.WriteLine(string.Format("---{0}:{1}", contentResponse.Code, contentResponse.Message)); return(new Tuple <T, Dictionary <string, TE> >(contentResponse.Response, contentResponse.Expansions)); } }
public IDirectedProtocolMessage GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary <string, string> fields) { if (fields.ContainsKey("age")) { if (this.signedMessages) { if (this.expiringMessages) { if (this.replayMessages) { return(new TestReplayProtectedMessage()); } return(new TestExpiringMessage()); } return(new TestSignedDirectedMessage()); } var result = new TestDirectedMessage(); if (fields.ContainsKey("GetOnly")) { result.HttpMethods = HttpDeliveryMethods.GetRequest; } return(result); } return(null); }
private WebConsumer CreateConsumer() { string consumerKey = "sampleconsumer"; string consumerSecret = "samplesecret"; var tokenManager = Session["WcfTokenManager"] as InMemoryTokenManager; if (tokenManager == null) { tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); Session["WcfTokenManager"] = tokenManager; } MessageReceivingEndpoint oauthEndpoint = new MessageReceivingEndpoint( new Uri("http://localhost:65169/OAuthServiceProvider/OAuth.ashx"), HttpDeliveryMethods.PostRequest); WebConsumer consumer = new WebConsumer( new ServiceProviderDescription { RequestTokenEndpoint = oauthEndpoint, UserAuthorizationEndpoint = oauthEndpoint, AccessTokenEndpoint = oauthEndpoint, TamperProtectionElements = new DotNetOpenAuth.Messaging.ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement(), }, }, tokenManager); return(consumer); }
public static XDocument GetDocList(ConsumerBase consumer, string accessToken, string nextEndpoint) { if (consumer == null) { throw new ArgumentNullException("consumer"); } var endpoint = GetDocsEntriesEndpoint; if (!string.IsNullOrEmpty(nextEndpoint)) { endpoint = new MessageReceivingEndpoint(nextEndpoint, HttpDeliveryMethods.GetRequest); } var extraData = new Dictionary <string, string>() /*{ {"GData-Version","3.0"} }*/; //var request = consumer.PrepareAuthorizedRequest(endpoint, accessToken, extraData); //var response = consumer.Channel.WebRequestHandler.GetResponse(request); //string body = response.GetResponseReader().ReadToEnd(); //XDocument result = XDocument.Parse(body); //return result; var request = consumer.PrepareAuthorizedRequest(endpoint, accessToken, extraData); // Enable gzip compression. Google only compresses the response for recognized user agent headers. - Mike Lim request.AutomaticDecompression = DecompressionMethods.GZip; request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.151 Safari/534.16"; var response = consumer.Channel.WebRequestHandler.GetResponse(request); string body = response.GetResponseReader().ReadToEnd(); XDocument result = XDocument.Parse(body); return(result); }
public static JObject GetUserInfo(WebConsumer consumer, int userid, String screenName, string accessToken) { var baseUri = "https://api.twitter.com/1.1/users/show.json"; String uri = String.Empty; if (userid > 0 && String.IsNullOrEmpty(screenName)) { uri = String.Concat(baseUri, "?user_id=", userid); } if (userid == 0 && !String.IsNullOrEmpty(screenName)) { uri = String.Concat(baseUri, "?screen_name=", screenName); } var endpoint = new MessageReceivingEndpoint(uri, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); IncomingWebResponse response = consumer.PrepareAuthorizedRequestAndSend(endpoint, accessToken); using (var responseReader = response.GetResponseReader()) { var result = responseReader.ReadToEnd(); return(JObject.Parse(result)); } }
/// <summary> /// Initializes a new instance of the <see cref="SignedMessageBase"/> class. /// </summary> /// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param> /// <param name="recipient">The URI that a directed message will be delivered to.</param> /// <param name="version">The OAuth version.</param> internal SignedMessageBase(MessageTransport transport, MessageReceivingEndpoint recipient, Version version) : base(MessageProtections.All, transport, recipient, version) { ITamperResistantOAuthMessage self = (ITamperResistantOAuthMessage)this; HttpDeliveryMethods methods = ((IDirectedProtocolMessage)this).HttpMethods; self.HttpMethod = MessagingUtilities.GetHttpVerb(methods); }
public static XDocument GetUserInfo(int userid, string accessToken) { var endpoint = new MessageReceivingEndpoint("http://api.twitter.com/1/users/show.xml?user_id=" + userid, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); IncomingWebResponse response = TwitterSignIn.PrepareAuthorizedRequestAndSend(endpoint, accessToken); var doc = XDocument.Load(XmlReader.Create(response.GetResponseReader())); return(doc); }
/// <summary> /// Initializes a new instance of the <see cref="SignedMessageBase"/> class. /// </summary> /// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param> /// <param name="recipient">The URI that a directed message will be delivered to.</param> internal SignedMessageBase(MessageTransport transport, MessageReceivingEndpoint recipient) : base(MessageProtections.All, transport, recipient) { ITamperResistantOAuthMessage self = (ITamperResistantOAuthMessage)this; HttpDeliveryMethods methods = ((IDirectedProtocolMessage)this).HttpMethods; self.HttpMethod = (methods & HttpDeliveryMethods.PostRequest) != 0 ? "POST" : "GET"; }
internal AccessProtectedResourceRequest CreateResourceRequest(MessageReceivingEndpoint endpoint) { Requires.NotNull(endpoint, "endpoint"); var message = new AccessProtectedResourceRequest(endpoint, Protocol.V10.Version); return(message); }