/// <summary> /// Method for getting a Site object containing information about the site /// </summary> /// <returns></returns> public Domain.Site Get() { // Build request URL List<string> requestUrlParameters = new List<string>(); // Do the request MessageReceivingEndpoint requestMessage = new MessageReceivingEndpoint(_provider.GetRequestUrl("/api/site/get", requestUrlParameters), HttpDeliveryMethods.GetRequest); XPathNavigator responseMessage = _provider.DoRequest(requestMessage); if (responseMessage == null) return null; // Get the site id XPathNavigator siteIdToken = responseMessage.SelectSingleNode("/response/site_id"); if (siteIdToken == null) return null; // Get the site name XPathNavigator siteNameToken = responseMessage.SelectSingleNode("/response/site_name"); if (siteNameToken == null) return null; // Get the product key XPathNavigator productKeyToken = responseMessage.SelectSingleNode("/response/product_key"); if (productKeyToken == null) return null; // Get the allow signup variable XPathNavigator allowSignupToken = responseMessage.SelectSingleNode("/response/allow_signup_p"); if (allowSignupToken == null) return null; // Get the site key XPathNavigator siteKeyToken = responseMessage.SelectSingleNode("/response/site_key"); if (siteKeyToken == null) return null; // Get the license id XPathNavigator licenseIdToken = responseMessage.SelectSingleNode("/response/license_id"); if (licenseIdToken == null) return null; // Get the domain XPathNavigator domainToken = responseMessage.SelectSingleNode("/response/domain"); if (domainToken == null) return null; // Create result try { Domain.Site result = new Domain.Site { SiteId = Helpers.ConvertStringToInteger(siteIdToken.Value), SiteName = siteNameToken.Value, SiteKey = siteKeyToken.Value, ProductKey = productKeyToken.Value, AllowSignup = (allowSignupToken.Value != "f"), LicenseId = Helpers.ConvertStringToInteger(licenseIdToken.Value), Domain = domainToken.Value }; return result; } catch { return null; } }
protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) { // See here for Field Selectors API http://developer.linkedin.com/docs/DOC-1014 const string profileRequestUrl = "http://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,industry,summary)"; string accessToken = response.AccessToken; var profileEndpoint = new MessageReceivingEndpoint(profileRequestUrl, HttpDeliveryMethods.GetRequest); HttpWebRequest request = this.WebWorker.PrepareAuthorizedRequest(profileEndpoint, accessToken); try { using (WebResponse profileResponse = request.GetResponse()) { using (Stream responseStream = profileResponse.GetResponseStream()) { XDocument document = XDocument.Load(responseStream); string userId = document.Root.Element("id").Value; string firstName = document.Root.Element("first-name").Value; string lastName = document.Root.Element("last-name").Value; string userName = firstName + " " + lastName; var extraData = new Dictionary<string, string>(); extraData.Add("accesstoken", accessToken); extraData.Add("name", userName); extraData.AddDataIfNotEmpty(document, "headline"); extraData.AddDataIfNotEmpty(document, "summary"); extraData.AddDataIfNotEmpty(document, "industry"); return new AuthenticationResult( isSuccessful: true, provider: this.ProviderName, providerUserId: userId, userName: userName, extraData: extraData); } } } catch (Exception exception) { return new AuthenticationResult(exception); } }
protected void getData_Click(object sender, EventArgs e) { WebConsumer consumer = CreateConsumer(); var serviceEndpoint = new MessageReceivingEndpoint(serviceTextBox.Text, HttpDeliveryMethods.GetRequest); var accessToken = Session["WcfAccessToken"] as string; if (accessToken == null) { throw new InvalidOperationException("No access token!"); } httpRequest = consumer.PrepareAuthorizedRequest(serviceEndpoint, accessToken); //httpRequest.BeginGetResponse(new AsyncCallback(GetResponse), null); var response = httpRequest.GetResponse(); using (var stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream)) { String data = reader.ReadToEnd(); JavaScriptSerializer js = new JavaScriptSerializer(); var dataObject = js.Deserialize<dynamic>(data); for (int i = 0; i < dataObject.Length; i++) { accountListBox.Items.Add(String.Format("{0} - {1} - {2} - {3}", dataObject[i]["Name"], dataObject[i]["Iban"], dataObject[i]["Balance"], dataObject[i]["Currency"])); } dataLabel.Text = data; } } }
/// <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> IDirectedProtocolMessage IMessageFactory.GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary <string, string> fields) { Contract.Requires <ArgumentNullException>(recipient != null); Contract.Requires <ArgumentNullException>(fields != null); throw new NotImplementedException(); }
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("http://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 = XDocument.Load(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); }
// * Create album // Implements http://www.23developer.com/api/album-create public int? Create(string title, string description = "", bool hide = false, int? userId = null) { // Verify required parameters if (String.IsNullOrEmpty(title)) return null; // Build request URL List<string> requestUrlParameters = new List<string>(); requestUrlParameters.Add("title=" + HttpUtility.UrlEncode(title)); if (!String.IsNullOrEmpty(description)) requestUrlParameters.Add("description=" + HttpUtility.UrlEncode(description)); if (hide) requestUrlParameters.Add("hide_p=1"); if (userId != null) requestUrlParameters.Add("user_id=" + userId); // Do the request MessageReceivingEndpoint requestMessage = new MessageReceivingEndpoint(_provider.GetRequestUrl("/api/album/create", requestUrlParameters), HttpDeliveryMethods.GetRequest); XPathNavigator responseMessage = _provider.DoRequest(requestMessage); if (responseMessage == null) return null; // Get the album id XPathNodeIterator albums = responseMessage.Select("/response/album_id"); if ((albums.MoveNext()) && (albums.Current != null)) return Helpers.ConvertStringToInteger(albums.Current.Value); // If nothing pops up, we'll return null return null; }
public OAuthManager(IHttpListenerManager listenerManager, DesktopConsumer consumer, MessageReceivingEndpoint serviceEndPoint) { _listenerManager = listenerManager; _consumer = consumer; _serviceEndPoint = serviceEndPoint; }
/// <summary> /// Get a list of players defined by the default request parameters /// </summary> /// <returns></returns> public List<Domain.Player> GetList() { // Build request URL List<string> requestUrlParameters = new List<string>(); // Do the request MessageReceivingEndpoint requestMessage = new MessageReceivingEndpoint(_provider.GetRequestUrl("/api/player/list", requestUrlParameters), HttpDeliveryMethods.GetRequest); XPathNavigator responseMessage = _provider.DoRequest(requestMessage); if (responseMessage == null) return null; // List all the videos XPathNodeIterator players = responseMessage.Select("/response/player"); List<Domain.Player> result = new List<Domain.Player>(); while (players.MoveNext()) { if (players.Current == null) return null; // Create the domain Tag Domain.Player playerModel = new Domain.Player { Default = (players.Current.GetAttribute("default_p", "") == "1"), Name = players.Current.GetAttribute("player_name", ""), Id = players.Current.GetAttribute("player_id", "") }; result.Add(playerModel); } return result; }
/// <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) { ErrorUtilities.VerifyArgumentNotNull(recipient, "recipient"); ErrorUtilities.VerifyArgumentNotNull(fields, "fields"); MessageBase message = null; if (fields.ContainsKey("oauth_consumer_key") && !fields.ContainsKey("oauth_token")) { message = new UnauthorizedTokenRequest(recipient); } 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(fields["oauth_token"]) == TokenType.AccessToken; message = tokenTypeIsAccessToken ? (MessageBase)new AccessProtectedResourceRequest(recipient) : new AuthorizedTokenRequest(recipient); } else { // fail over to the message with no required fields at all. message = new UserAuthorizationRequest(recipient); } if (message != null) { message.SetAsIncoming(); } return message; }
/// <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"; }
/// <summary> /// Gets the message type that best fits the given incoming request data. /// </summary> /// <param name="recipient">The recipient of the incoming data. Typically not used, but included just in case.</param> /// <param name="fields">The data of the incoming message.</param> /// <returns> /// The message type that matches the incoming data; or <c>null</c> if no match. /// </returns> /// <exception cref="ProtocolException">May be thrown if the incoming data is ambiguous.</exception> protected virtual MessageDescription GetMessageDescription(MessageReceivingEndpoint recipient, IDictionary <string, string> fields) { Requires.NotNull(recipient, "recipient"); Requires.NotNull(fields, "fields"); var matches = this.requestMessageTypes.Keys .Where(message => message.CheckMessagePartsPassBasicValidation(fields)) .OrderByDescending(message => CountInCommon(message.Mapping.Keys, fields.Keys)) .ThenByDescending(message => message.Mapping.Count) .CacheGeneratedResults(); var match = matches.FirstOrDefault(); if (match != null) { if (Logger.Messaging.IsWarnEnabled && matches.Count() > 1) { Logger.Messaging.WarnFormat( "Multiple message types seemed to fit the incoming data: {0}", matches.ToStringDeferred()); } return(match); } else { // No message type matches the incoming data. return(null); } }
/// <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); }
// * Create user // Implements http://www.23developer.com/api/user-create /// <summary>Create a user specified by an e-mail address, username, password, full name, timezone and site admin rigts specification</summary> public int? Create(string email, string username = null, string password = null, string fullName = null, Timezone timezone = Timezone.CET, bool siteAdmin = false) { // Verify required parameters if (String.IsNullOrEmpty(email)) return null; // Build request URL List<string> requestUrlParameters = new List<string>(); requestUrlParameters.Add("email=" + HttpUtility.UrlEncode(email)); if (!String.IsNullOrEmpty(username)) requestUrlParameters.Add("username="******"password="******"full_name=" + HttpUtility.UrlEncode(fullName)); requestUrlParameters.Add("timezone=" + HttpUtility.UrlEncode(RequestValues.Get(timezone))); if (siteAdmin) requestUrlParameters.Add("site_admin=1"); // Do the request MessageReceivingEndpoint requestMessage = new MessageReceivingEndpoint(_provider.GetRequestUrl("/api/user/create", requestUrlParameters), HttpDeliveryMethods.GetRequest); XPathNavigator responseMessage = _provider.DoRequest(requestMessage); if (responseMessage == null) return null; // Get the User id XPathNodeIterator users = responseMessage.Select("/response/user_id"); if ((users.MoveNext()) && (users.Current != null)) return Helpers.ConvertStringToInteger(users.Current.Value); // If nothing pops up, we'll return null return null; }
/// <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> IDirectedProtocolMessage IMessageFactory.GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary <string, string> fields) { Requires.NotNull(recipient, "recipient"); Requires.NotNull(fields, "fields"); throw new NotImplementedException(); }
/// <summary> /// Initializes a new instance of the <see cref="MessageBase"/> class for direct requests or indirect messages. /// </summary> /// <param name="protectionRequired">The level of protection the message requires.</param> /// <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> protected MessageBase(MessageProtections protectionRequired, MessageTransport transport, MessageReceivingEndpoint recipient, Version version) { Contract.Requires<ArgumentNullException>(recipient != null); Contract.Requires<ArgumentNullException>(version != null); this.protectionRequired = protectionRequired; this.transport = transport; this.recipient = recipient; this.Version = version; }
/// <summary> /// Initializes a new instance of the <see cref="CoordinatingHttpRequestInfo"/> class /// that will generate a message when the <see cref="Message"/> property getter is called. /// </summary> /// <param name="channel">The channel.</param> /// <param name="messageFactory">The message factory.</param> /// <param name="messageData">The message data.</param> /// <param name="recipient">The recipient.</param> internal CoordinatingHttpRequestInfo(Channel channel, IMessageFactory messageFactory, IDictionary<string, string> messageData, MessageReceivingEndpoint recipient) : this(recipient) { Contract.Requires(channel != null); Contract.Requires(messageFactory != null); Contract.Requires(messageData != null); this.channel = channel; this.messageFactory = messageFactory; this.messageData = messageData; }
/// <summary> /// Initializes a new instance of the <see cref="MessageBase"/> class for direct requests or indirect messages. /// </summary> /// <param name="protectionRequired">The level of protection the message requires.</param> /// <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> protected MessageBase(MessageProtections protectionRequired, MessageTransport transport, MessageReceivingEndpoint recipient, Version version) { Requires.NotNull(recipient, "recipient"); Requires.NotNull(version, "version"); this.protectionRequired = protectionRequired; this.transport = transport; this.recipient = recipient; this.Version = version; }
/// <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) { ErrorUtilities.VerifyArgumentNotNull(recipient, "recipient"); ErrorUtilities.VerifyArgumentNotNull(fields, "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 AssociateDiffieHellmanRequest(protocol.Version, recipient.Location); } else { message = new AssociateUnencryptedRequest(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.cancel) || (string.Equals(mode, protocol.Args.Mode.setup_needed) && (protocol.Version.Major >= 2 || fields.ContainsKey(protocol.openid.user_setup_url)))) { message = new NegativeAssertionResponse(protocol.Version, recipient.Location, mode); } else if (string.Equals(mode, protocol.Args.Mode.id_res)) { if (fields.ContainsKey(protocol.openid.identity)) { message = new PositiveAssertionResponse(protocol.Version, recipient.Location); } else { ErrorUtilities.VerifyProtocol(!fields.ContainsKey(protocol.openid.claimed_id), OpenIdStrings.IdentityAndClaimedIdentifierMustBeBothPresentOrAbsent); message = new IndirectSignedResponse(protocol.Version, recipient.Location); } } else if (string.Equals(mode, protocol.Args.Mode.check_authentication)) { message = new CheckAuthenticationRequest(protocol.Version, recipient.Location); } else if (string.Equals(mode, protocol.Args.Mode.error)) { message = new IndirectErrorResponse(protocol.Version, recipient.Location); } else { ErrorUtilities.ThrowProtocol(MessagingStrings.UnexpectedMessagePartValue, protocol.openid.mode, mode); } } if (message != null) { message.SetAsIncoming(); } return message; }
public override IDirectedProtocolMessage GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary<string, string> fields) { var message = base.GetNewRequestMessage(recipient, fields); // inject our own type here to replace the standard one if (message is UnauthorizedTokenRequest) { message = new RequestScopedTokenMessage(recipient, message.Version); } return message; }
public OAuthManager(IHttpListenerManager listenerManager, DesktopConsumer consumer, MessageReceivingEndpoint serviceEndPoint) { this._listenerManager = listenerManager; this._consumer = consumer; this._serviceEndPoint = serviceEndPoint; // Trying to fix https://github.com/flickr-downloadr/flickr-downloadr-gtk/issues/15 // From the comment in this SO answer: // http://stackoverflow.com/questions/1186682/expectation-failed-when-trying-to-update-twitter-status/2025073#2025073 ServicePointManager.FindServicePoint(this._serviceEndPoint.Location).Expect100Continue = false; }
public void HttpSignatureVerification() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("http://localtest", HttpDeliveryMethods.GetRequest); ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint, Protocol.Default.Version); message.ConsumerSecret = "cs"; message.TokenSecret = "ts"; message.SignatureMethod = "PLAINTEXT"; message.Signature = "cs%26ts"; Assert.IsNull(target.ProcessIncomingMessage(message), "PLAINTEXT signature binding element should refuse to participate in non-encrypted messages."); }
public void HttpsSignatureGeneration() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest); ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint, Protocol.Default.Version); message.ConsumerSecret = "cs"; message.TokenSecret = "ts"; Assert.IsNotNull(target.ProcessOutgoingMessage(message)); Assert.AreEqual("PLAINTEXT", message.SignatureMethod); Assert.AreEqual("cs&ts", message.Signature); }
public void HttpsSignatureVerification() { MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest); ITamperProtectionChannelBindingElement target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint, Protocol.Default.Version); message.ConsumerSecret = "cs"; message.TokenSecret = "ts"; message.SignatureMethod = "PLAINTEXT"; message.Signature = "cs&ts"; Assert.IsNotNull(target.ProcessIncomingMessage(message)); }
public void HttpsSignatureVerificationNotApplicable() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest); ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint, Protocol.Default.Version); message.ConsumerSecret = "cs"; message.TokenSecret = "ts"; message.SignatureMethod = "ANOTHERALGORITHM"; message.Signature = "somethingelse"; Assert.AreEqual(MessageProtections.None, target.ProcessIncomingMessage(message), "PLAINTEXT binding element should opt-out where it doesn't understand."); }
protected OAuthAuthenticator( ServiceProviderDescription description, Func<string, AuthResult.Data> selector, string endpoint, string consumerKey, string consumerSecret) { _endpoint = new MessageReceivingEndpoint(endpoint, HttpDeliveryMethods.GetRequest); _selector = selector; _client = new WebConsumer(description, new InMemoryTokenManager(consumerKey, consumerSecret)); }
public void AccessTokenUriTest() { var target = new ServiceProviderDescription(); MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/accesstoken", HttpDeliveryMethods.GetRequest); MessageReceivingEndpoint actual; target.AccessTokenEndpoint = expected; actual = target.AccessTokenEndpoint; Assert.AreEqual(expected, actual); target.AccessTokenEndpoint = null; Assert.IsNull(target.AccessTokenEndpoint); }
public void UserAuthorizationUriTest() { var target = new ServiceProviderHostDescription(); var expected = new MessageReceivingEndpoint("http://localhost/authorization", HttpDeliveryMethods.GetRequest); MessageReceivingEndpoint actual; target.UserAuthorizationEndpoint = expected; actual = target.UserAuthorizationEndpoint; Assert.AreEqual(expected, actual); target.UserAuthorizationEndpoint = null; Assert.IsNull(target.UserAuthorizationEndpoint); }
/// <summary> /// Initializes a new instance of the <see cref="CoordinatingHttpRequestInfo"/> class /// that will not generate any message. /// </summary> /// <param name="recipient">The recipient.</param> internal CoordinatingHttpRequestInfo(MessageReceivingEndpoint recipient) { this.recipient = recipient; if (recipient != null) { this.UrlBeforeRewriting = recipient.Location; } if (recipient == null || (recipient.AllowedMethods & HttpDeliveryMethods.GetRequest) != 0) { this.HttpMethod = "GET"; } else if ((recipient.AllowedMethods & HttpDeliveryMethods.PostRequest) != 0) { this.HttpMethod = "POST"; } }
/// <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) { ErrorUtilities.VerifyArgumentNotNull(recipient, "recipient"); ErrorUtilities.VerifyArgumentNotNull(fields, "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); } }
public void HttpSignatureGeneration() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("http://localtest", HttpDeliveryMethods.GetRequest); ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint, Protocol.Default.Version); message.ConsumerSecret = "cs"; message.TokenSecret = "ts"; // Since this is (non-encrypted) HTTP, so the plain text signer should not be used Assert.IsNull(target.ProcessOutgoingMessage(message)); Assert.IsNull(message.SignatureMethod); Assert.IsNull(message.Signature); }
/// <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 virtual IDirectedProtocolMessage GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary <string, string> fields) { MessageDescription matchingType = this.GetMessageDescription(recipient, fields); if (matchingType != null) { return(this.InstantiateAsRequest(matchingType, recipient)); } else { return(null); } }
internal static UnauthorizedTokenRequest CreateTestRequestTokenMessage(MessageDescriptionCollection messageDescriptions, MessageReceivingEndpoint endpoint) { endpoint = endpoint ?? new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest); UnauthorizedTokenRequest message = new UnauthorizedTokenRequest(endpoint, Protocol.V10.Version); message.ConsumerKey = "nerdbank.org"; ((ITamperResistantOAuthMessage)message).ConsumerSecret = "nerdbanksecret"; var signedMessage = (ITamperResistantOAuthMessage)message; signedMessage.HttpMethod = "GET"; signedMessage.SignatureMethod = "HMAC-SHA1"; MessageDictionary dictionary = messageDescriptions.GetAccessor(message); dictionary["oauth_timestamp"] = "1222665749"; dictionary["oauth_nonce"] = "fe4045a3f0efdd1e019fa8f8ae3f5c38"; dictionary["scope"] = "http://www.google.com/m8/feeds/"; return message; }
/// <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: /// UserAuthorizationResponse /// </remarks> public virtual IDirectedProtocolMessage GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary<string, string> fields) { MessageBase message = null; if (fields.ContainsKey("oauth_token")) { Protocol protocol = fields.ContainsKey("oauth_verifier") ? Protocol.V10a : Protocol.V10; message = new UserAuthorizationResponse(recipient.Location, protocol.Version); } if (message != null) { message.SetAsIncoming(); } return message; }
/// <summary> /// Initializes a new instance of the <see cref="CoordinatingHttpRequestInfo"/> class /// that will generate a message when the <see cref="Message"/> property getter is called. /// </summary> /// <param name="channel">The channel.</param> /// <param name="messageFactory">The message factory.</param> /// <param name="messageData">The message data.</param> /// <param name="recipient">The recipient.</param> /// <param name="cookies">Cookies included in the incoming request.</param> internal CoordinatingHttpRequestInfo( Channel channel, IMessageFactory messageFactory, IDictionary<string, string> messageData, MessageReceivingEndpoint recipient, HttpCookieCollection cookies) : this(recipient, cookies) { Requires.NotNull(channel, "channel"); Requires.NotNull(messageFactory, "messageFactory"); Requires.NotNull(messageData, "messageData"); this.channel = channel; this.messageData = messageData; this.messageFactory = messageFactory; }
/// <summary> /// Instantiates the given request message type. /// </summary> /// <param name="messageDescription">The message description.</param> /// <param name="recipient">The recipient.</param> /// <returns>The instantiated message. Never null.</returns> protected virtual IDirectedProtocolMessage InstantiateAsRequest(MessageDescription messageDescription, MessageReceivingEndpoint recipient) { Requires.NotNull(messageDescription, "messageDescription"); Requires.NotNull(recipient, "recipient"); Contract.Ensures(Contract.Result <IDirectedProtocolMessage>() != null); ConstructorInfo ctor = this.requestMessageTypes[messageDescription]; return((IDirectedProtocolMessage)ctor.Invoke(new object[] { recipient.Location, messageDescription.MessageVersion })); }
/// <summary> /// Deserializes a dictionary of values into a message. /// </summary> /// <param name="fields">The dictionary of values that were read from an HTTP request or response.</param> /// <param name="recipient">Information about where the message was been directed. Null for direct response messages.</param> /// <returns>The deserialized message, or null if no message could be recognized in the provided data.</returns> protected virtual IProtocolMessage Receive(Dictionary <string, string> fields, MessageReceivingEndpoint recipient) { ErrorUtilities.VerifyArgumentNotNull(fields, "fields"); IProtocolMessage message = this.MessageFactory.GetNewRequestMessage(recipient, fields); // If there was no data, or we couldn't recognize it as a message, abort. if (message == null) { return(null); } // We have a message! Assemble it. var serializer = MessageSerializer.Get(message.GetType()); serializer.Deserialize(fields, message); return(message); }