public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            var user = _context.Users.Where(x => x.Id == _requestingUserId).First();
            var data = new OAuthData
            {
                Token         = response.Token,
                Secret        = response.TokenSecret,
                TokenType     = TokenType.RequestToken,
                TokenProvider = _tokenProvider,
                LinkedInUsers = new List <User> {
                    user
                }
            };

            _context.OAuthData.Add(data);
            _context.SaveChanges();
        }
示例#2
0
        protected internal UserAuthorizationRequest PrepareRequestUserAuthorization(Uri callback, IDictionary <string, string> requestParameters, IDictionary <string, string> redirectParameters, out string requestToken)
        {
            // Obtain an unauthorized request token.  Assume the OAuth version given in the service description.
            var token = new UnauthorizedTokenRequest(this.ServiceProvider.RequestTokenEndpoint, this.ServiceProvider.Version)
            {
                ConsumerKey = this.ConsumerKey,
                Callback    = callback,
            };
            var tokenAccessor = this.Channel.MessageDescriptions.GetAccessor(token);

            tokenAccessor.AddExtraParameters(requestParameters);
            var requestTokenResponse = this.Channel.Request <UnauthorizedTokenResponse>(token);

            this.TokenManager.StoreNewRequestToken(token, requestTokenResponse);

            // Fine-tune our understanding of the SP's supported OAuth version if it's wrong.
            if (this.ServiceProvider.Version != requestTokenResponse.Version)
            {
                Logger.OAuth.WarnFormat("Expected OAuth service provider at endpoint {0} to use OAuth {1} but {2} was detected.  Adjusting service description to new version.", this.ServiceProvider.RequestTokenEndpoint.Location, this.ServiceProvider.Version, requestTokenResponse.Version);
                this.ServiceProvider.ProtocolVersion = Protocol.Lookup(requestTokenResponse.Version).ProtocolVersion;
            }

            // Request user authorization.  The OAuth version will automatically include
            // or drop the callback that we're setting here.
            ITokenContainingMessage assignedRequestToken = requestTokenResponse;
            var requestAuthorization = new UserAuthorizationRequest(this.ServiceProvider.UserAuthorizationEndpoint, assignedRequestToken.Token, requestTokenResponse.Version)
            {
                Callback = callback,
            };
            var requestAuthorizationAccessor = this.Channel.MessageDescriptions.GetAccessor(requestAuthorization);

            requestAuthorizationAccessor.AddExtraParameters(redirectParameters);
            requestToken = requestAuthorization.RequestToken;
            return(requestAuthorization);
        }
示例#3
0
 /// <summary>
 /// Stores a newly generated unauthorized request token, secret, and optional
 /// application-specific parameters for later recall.
 /// </summary>
 /// <param name="request">The request message that resulted in the generation of a new unauthorized request token.</param>
 /// <param name="response">The response message that includes the unauthorized request token.</param>
 /// <exception cref="ArgumentException">Thrown if the consumer key is not registered, or a required parameter was not found in the parameters collection.</exception>
 /// <remarks>
 /// Request tokens stored by this method SHOULD NOT associate any user account with this token.
 /// It usually opens up security holes in your application to do so.  Instead, you associate a user
 /// account with access tokens (not request tokens) in the <see cref="ExpireRequestTokenAndStoreNewAccessToken"/>
 /// method.
 /// </remarks>
 public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
 {
     using (var db = new DbManager(_dbId))
     {
         db.ExecuteNonQuery(new SqlInsert(TOKEN_TABLE, true).InColumnValue("token", response.Token).InColumnValue("token_secret", response.TokenSecret).InColumnValue("request_token", true));
     }
 }
示例#4
0
        /// <summary>
        /// Stores a newly generated unauthorized request token, secret, and optional
        /// application-specific parameters for later recall.
        /// </summary>
        /// <param name="request">The request message that resulted in the generation of a new unauthorized request token.</param>
        /// <param name="response">The response message that includes the unauthorized request token.</param>
        /// <exception cref="ArgumentException">Thrown if the consumer key is not registered, or a required parameter was not found in the parameters collection.</exception>
        /// <remarks>
        /// Request tokens stored by this method SHOULD NOT associate any user account with this token.
        /// It usually opens up security holes in your application to do so.  Instead, you associate a user
        /// account with access tokens (not request tokens) in the <see cref="ExpireRequestTokenAndStoreNewAccessToken"/>
        /// method.
        /// </remarks>
        public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
        {
            Consumer consumer;

            try
            {
                consumer = Database.DataContext.Consumers.First(c => c.ConsumerKey == request.ConsumerKey);
            }
            catch (InvalidOperationException)
            {
                throw new ArgumentOutOfRangeException();
            }

            var token = new IssuedRequestToken
            {
                Callback    = request.Callback,
                Consumer    = consumer,
                Token       = response.Token,
                TokenSecret = response.TokenSecret,
            };
            string scope;

            if (request.ExtraData.TryGetValue("scope", out scope))
            {
                token.Scope = scope;
            }
            Database.DataContext.AddToIssuedTokens(token);
            Database.DataContext.SaveChanges();
        }
示例#5
0
        /// <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);
            }
        }
示例#6
0
        public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
        {
            var dictionary = LoadJson();

            dictionary[response.Token] = response.TokenSecret;
            SaveJson(dictionary);
        }
 public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
 {
     this.tokens.Add(new TokenInfo {
         ConsumerKey = request.ConsumerKey, Token = response.Token, Secret = response.TokenSecret
     });
     this.requestTokens.Add(response.Token, false);
 }
        /// <summary>
        /// Obtains an access token for a new account at the Service Provider via 2-legged OAuth.
        /// </summary>
        /// <param name="requestParameters">Any applicable parameters to include in the query string of the token request.</param>
        /// <returns>The access token.</returns>
        /// <remarks>
        /// The token secret is stored in the <see cref="TokenManager"/>.
        /// </remarks>
        public string RequestNewClientAccount(IDictionary <string, string> requestParameters = null)
        {
            // Obtain an unauthorized request token.  Force use of OAuth 1.0 (not 1.0a) so that
            // we are not expected to provide an oauth_verifier which doesn't apply in 2-legged OAuth.
            var token = new UnauthorizedTokenRequest(this.ServiceProvider.RequestTokenEndpoint, Protocol.V10.Version)
            {
                ConsumerKey = this.ConsumerKey,
            };
            var tokenAccessor = this.Channel.MessageDescriptions.GetAccessor(token);

            tokenAccessor.AddExtraParameters(requestParameters);
            var requestTokenResponse = this.Channel.Request <UnauthorizedTokenResponse>(token);

            this.TokenManager.StoreNewRequestToken(token, requestTokenResponse);

            var requestAccess = new AuthorizedTokenRequest(this.ServiceProvider.AccessTokenEndpoint, Protocol.V10.Version)
            {
                RequestToken = requestTokenResponse.RequestToken,
                ConsumerKey  = this.ConsumerKey,
            };
            var grantAccess = this.Channel.Request <AuthorizedTokenResponse>(requestAccess);

            this.TokenManager.ExpireRequestTokenAndStoreNewAccessToken(this.ConsumerKey, requestTokenResponse.RequestToken, grantAccess.AccessToken, grantAccess.TokenSecret);
            return(grantAccess.AccessToken);
        }
示例#9
0
        public void BaseSignatureStringTest()
        {
            // Tests a message sent by HTTP GET, with no query string included in the endpoint.
            UnauthorizedTokenRequest message = CreateTestRequestTokenMessage(
                this.MessageDescriptions,
                new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest));

            Assert.AreEqual(
                "GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_consumer_key%3Dnerdbank.org%26oauth_nonce%3Dfe4045a3f0efdd1e019fa8f8ae3f5c38%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1222665749%26oauth_version%3D1.0%26scope%3Dhttp%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds%252F",
                SigningBindingElementBase.ConstructSignatureBaseString(message, this.MessageDescriptions.GetAccessor(message)));

            // Test HTTP GET with an attached query string.  We're elevating the scope parameter to the query string
            // and removing it from the extradata dictionary.  This should NOT affect the base signature string.
            message = CreateTestRequestTokenMessage(
                this.MessageDescriptions,
                new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken?scope=http://www.google.com/m8/feeds/", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest));
            message.ExtraData.Remove("scope");             // remove it from ExtraData since we put it in the URL
            Assert.AreEqual(
                "GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_consumer_key%3Dnerdbank.org%26oauth_nonce%3Dfe4045a3f0efdd1e019fa8f8ae3f5c38%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1222665749%26oauth_version%3D1.0%26scope%3Dhttp%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds%252F",
                SigningBindingElementBase.ConstructSignatureBaseString(message, this.MessageDescriptions.GetAccessor(message)));

            // Test HTTP POST, with query string as well
            message = CreateTestRequestTokenMessage(
                this.MessageDescriptions,
                new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken?scope=http://www.google.com/m8/feeds/", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest));
            message.ExtraData.Remove("scope");             // remove it from ExtraData since we put it in the URL
            Assert.AreEqual(
                "GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_consumer_key%3Dnerdbank.org%26oauth_nonce%3Dfe4045a3f0efdd1e019fa8f8ae3f5c38%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1222665749%26oauth_version%3D1.0%26scope%3Dhttp%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds%252F",
                SigningBindingElementBase.ConstructSignatureBaseString(message, this.MessageDescriptions.GetAccessor(message)));

            // Test HTTP POST, with query string, but not using the Authorization header
            message = CreateTestRequestTokenMessage(
                this.MessageDescriptions,
                new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken?scope=http://www.google.com/m8/feeds/", HttpDeliveryMethods.PostRequest));
            message.ExtraData.Remove("scope");             // remove it from ExtraData since we put it in the URL
            Assert.AreEqual(
                "GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_consumer_key%3Dnerdbank.org%26oauth_nonce%3Dfe4045a3f0efdd1e019fa8f8ae3f5c38%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1222665749%26oauth_version%3D1.0%26scope%3Dhttp%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds%252F",
                SigningBindingElementBase.ConstructSignatureBaseString(message, this.MessageDescriptions.GetAccessor(message)));

            // Test for when oauth_version isn't explicitly included in the message by the consumer.
            message = CreateTestRequestTokenMessageNoOAuthVersion(
                this.MessageDescriptions,
                new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken?scope=http://www.google.com/m8/feeds/", HttpDeliveryMethods.GetRequest));
            message.ExtraData.Remove("scope");             // remove it from ExtraData since we put it in the URL
            Assert.AreEqual(
                "GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_consumer_key%3Dnerdbank.org%26oauth_nonce%3Dfe4045a3f0efdd1e019fa8f8ae3f5c38%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1222665749%26scope%3Dhttp%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds%252F",
                SigningBindingElementBase.ConstructSignatureBaseString(message, this.MessageDescriptions.GetAccessor(message)));

            // This is a simulation of receiving the message, where the query string is still in the URL,
            // but has been read into ExtraData, so parameters in the query string appear twice.
            message = CreateTestRequestTokenMessage(
                this.MessageDescriptions,
                new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken?scope=http://www.google.com/m8/feeds/", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest));
            Assert.AreEqual(
                "GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_consumer_key%3Dnerdbank.org%26oauth_nonce%3Dfe4045a3f0efdd1e019fa8f8ae3f5c38%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1222665749%26oauth_version%3D1.0%26scope%3Dhttp%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds%252F",
                SigningBindingElementBase.ConstructSignatureBaseString(message, this.MessageDescriptions.GetAccessor(message)));
        }
示例#10
0
        public void SignatureTest()
        {
            UnauthorizedTokenRequest message = SigningBindingElementBaseTests.CreateTestRequestTokenMessage(this.MessageDescriptions, null);

            HmacSha1SigningBindingElement_Accessor hmac = new HmacSha1SigningBindingElement_Accessor();

            hmac.Channel = new TestChannel(this.MessageDescriptions);
            Assert.AreEqual("kR0LhH8UqylaLfR/esXVVlP4sQI=", hmac.GetSignature(message));
        }
示例#11
0
        /// <summary>
        /// Prepares a message containing an unauthorized token for the Consumer to use in a
        /// user agent redirect for subsequent authorization.
        /// </summary>
        /// <param name="request">The token request message the Consumer sent that the Service Provider is now responding to.</param>
        /// <returns>The response message to send using the <see cref="Channel"/>, after optionally adding extra data to it.</returns>
        public UnauthorizedTokenResponse PrepareUnauthorizedTokenMessage(UnauthorizedTokenRequest request)
        {
            Contract.Requires <ArgumentNullException>(request != null);

            string token  = this.TokenGenerator.GenerateRequestToken(request.ConsumerKey);
            string secret = this.TokenGenerator.GenerateSecret();
            UnauthorizedTokenResponse response = new UnauthorizedTokenResponse(request, token, secret);

            return(response);
        }
示例#12
0
        /// <summary>
        /// Prepares a message containing an unauthorized token for the Consumer to use in a
        /// user agent redirect for subsequent authorization.
        /// </summary>
        /// <param name="request">The token request message the Consumer sent that the Service Provider is now responding to.</param>
        /// <returns>The response message to send using the <see cref="Channel"/>, after optionally adding extra data to it.</returns>
        public UnauthorizedTokenResponse PrepareUnauthorizedTokenMessage(UnauthorizedTokenRequest request)
        {
            Requires.NotNull(request, "request");

            string token  = this.TokenGenerator.GenerateRequestToken(request.ConsumerKey);
            string secret = this.TokenGenerator.GenerateSecret();
            UnauthorizedTokenResponse response = new UnauthorizedTokenResponse(request, token, secret);

            return(response);
        }
示例#13
0
        /// <summary>
        /// Prepares a message containing an unauthorized token for the Consumer to use in a
        /// user agent redirect for subsequent authorization.
        /// </summary>
        /// <param name="request">The token request message the Consumer sent that the Service Provider is now responding to.</param>
        /// <returns>The response message to send using the <see cref="Channel"/>, after optionally adding extra data to it.</returns>
        public UnauthorizedTokenResponse PrepareUnauthorizedTokenMessage(UnauthorizedTokenRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            string token  = this.TokenGenerator.GenerateRequestToken(request.ConsumerKey);
            string secret = this.TokenGenerator.GenerateSecret();
            UnauthorizedTokenResponse response = new UnauthorizedTokenResponse(request, token, secret);

            return(response);
        }
        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 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 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.");
        }
示例#17
0
        public void ProcessRequest(HttpContext context)
        {
            IProtocolMessage         request      = m_Provider.ReadRequest();
            UnauthorizedTokenRequest requestToken = null;
            UserAuthorizationRequest requestAuth  = null;
            AuthorizedTokenRequest   requestAccessToken;

            if ((requestToken = request as UnauthorizedTokenRequest) != null)
            {
                UnauthorizedTokenResponse response = m_Provider.PrepareUnauthorizedTokenMessage(requestToken);
                m_Provider.Channel.Send(response);
            }
            else if ((requestAuth = request as UserAuthorizationRequest) != null)
            {
                string token = ((ITokenContainingMessage)requestAuth).Token;

                ((TokenProvider)m_Provider.TokenManager).UpdatePendingUserAuthorizationRequest(token, requestAuth);

                TokenProvider.SetTokenCookie(token);

                if (context == null)
                {
                    throw new ArgumentNullException("context");
                }

                context.Response.Redirect(ActionProvider.FindAction(ActionProvider.OAuthPageActionId).AbsoluteNavigateUrl);
            }
            else if ((requestAccessToken = request as AuthorizedTokenRequest) != null)
            {
                AuthorizedTokenResponse response = m_Provider.PrepareAccessTokenMessage(requestAccessToken);

                OAuthDataSet.OAuthTokenRow row = (OAuthDataSet.OAuthTokenRow)m_Provider.TokenManager.GetAccessToken(response.AccessToken);
                response.ExtraData.Add(new KeyValuePair <string, string>("api_token", LoginProvider.Current.GetToken(row.LoginId)));

                if (!row.IsOrganizationIdNull())
                {
                    response.ExtraData.Add(new KeyValuePair <string, string>("org", OrganizationProvider.GetOrganization(row.OrganizationId).PseudoId));
                    if (!row.IsInstanceIdNull())
                    {
                        response.ExtraData.Add(new KeyValuePair <string, string>("dept", InstanceProvider.GetInstance(row.InstanceId, row.OrganizationId).PseudoId));
                    }
                }

                m_Provider.Channel.Send(response);
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
        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.");
        }
        /// <summary> </summary>
        public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
        {
            RequestScopedTokenMessage scopedRequest = (RequestScopedTokenMessage)request;
            var        consumer = GlobalApplication.Consumers.Single(consumerRow => consumerRow.Key == request.ConsumerKey);
            string     scope    = scopedRequest.Scope;
            OAuthToken newToken = new OAuthToken {
                Consumer    = consumer,
                Token       = response.Token,
                TokenSecret = response.TokenSecret,
                IssueDate   = DateTime.UtcNow,
                Scope       = scope,
            };

            GlobalApplication.AuthTokens.Add(newToken);
        }
        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);
        }
示例#21
0
        public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
        {
            RequestScopedTokenMessage scopedRequest = (RequestScopedTokenMessage)request;
            var        consumer = Global.DataContext.OAuthConsumers.Single(consumerRow => consumerRow.ConsumerKey == request.ConsumerKey);
            string     scope    = scopedRequest.Scope;
            OAuthToken newToken = new OAuthToken {
                OAuthConsumer = consumer,
                Token         = response.Token,
                TokenSecret   = response.TokenSecret,
                IssueDate     = DateTime.UtcNow,
                Scope         = scope,
            };

            Global.DataContext.OAuthTokens.InsertOnSubmit(newToken);
            Global.DataContext.SubmitChanges();
        }
示例#22
0
        public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
        {
            if ((request != null) && (response != null))
            {
                string callback = string.Empty;
                if (request.Callback != null)
                {
                    callback = request.Callback.AbsoluteUri;
                }

                using (OAuthTokenTableAdapter adapter = new OAuthTokenTableAdapter())
                {
                    adapter.Insert(Guid.NewGuid(), response.Token, response.TokenSecret, (int)OAuthTokenType.UnauthorizedRequestToken
                                   , GetConsumerId(request.ConsumerKey), ((IMessage)request).Version.ToString(), string.Empty, null, string.Empty, callback, DateTime.UtcNow, null, null, 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);
        }
示例#24
0
        internal static UnauthorizedTokenRequest CreateTestRequestTokenMessageNoOAuthVersion(MessageDescriptionCollection messageDescriptions, MessageReceivingEndpoint endpoint)
        {
            endpoint = endpoint ?? new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest);
            var parts = new Dictionary <string, string>();

            parts["oauth_consumer_key"] = "nerdbank.org";
            parts["oauth_timestamp"]    = "1222665749";
            parts["oauth_nonce"]        = "fe4045a3f0efdd1e019fa8f8ae3f5c38";
            parts["scope"] = "http://www.google.com/m8/feeds/";
            parts["oauth_signature_method"] = "HMAC-SHA1";
            parts["oauth_signature"]        = "anything non-empty";

            UnauthorizedTokenRequest message    = new UnauthorizedTokenRequest(endpoint, Protocol.V10.Version);
            MessageDictionary        dictionary = messageDescriptions.GetAccessor(message);

            MessageSerializer.Get(typeof(UnauthorizedTokenRequest)).Deserialize(parts, dictionary);

            return(message);
        }
示例#25
0
        protected internal UserAuthorizationRequest PrepareRequestUserAuthorization(Uri callback, IDictionary <string, string> requestParameters, IDictionary <string, string> redirectParameters, out string requestToken)
        {
            // Obtain an unauthorized request token.
            var token = new UnauthorizedTokenRequest(this.ServiceProvider.RequestTokenEndpoint)
            {
                ConsumerKey = this.ConsumerKey,
            };

            token.AddExtraParameters(requestParameters);
            var requestTokenResponse = this.Channel.Request <UnauthorizedTokenResponse>(token);

            this.TokenManager.StoreNewRequestToken(token, requestTokenResponse);

            // Request user authorization.
            ITokenContainingMessage assignedRequestToken = requestTokenResponse;
            var requestAuthorization = new UserAuthorizationRequest(this.ServiceProvider.UserAuthorizationEndpoint, assignedRequestToken.Token)
            {
                Callback = callback,
            };

            requestAuthorization.AddExtraParameters(redirectParameters);
            requestToken = requestAuthorization.RequestToken;
            return(requestAuthorization);
        }
        /// <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);
        }
示例#27
0
 public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
 {
     throw new NotImplementedException();
 }
示例#28
0
 /// <summary>
 /// Stores a newly generated unauthorized request token, secret, and optional
 /// application-specific parameters for later recall.
 /// </summary>
 /// <param name="request">The request message that resulted in the generation of a new unauthorized request token.</param>
 /// <param name="response">The response message that includes the unauthorized request token.</param>
 /// <exception cref="ArgumentException">Thrown if the consumer key is not registered, or a required parameter was not found in the parameters collection.</exception>
 /// <remarks>
 /// Request tokens stored by this method SHOULD NOT associate any user account with this token.
 /// It usually opens up security holes in your application to do so.  Instead, you associate a user
 /// account with access tokens (not request tokens) in the <see cref="ExpireRequestTokenAndStoreNewAccessToken"/>
 /// method.
 /// </remarks>
 public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
 {
     _tokensAndSecrets[response.Token] = response.TokenSecret;
 }
 public void StoreNewRequestToken(UnauthorizedTokenRequest request,
                                  ITokenSecretContainingMessage response)
 {
     this.tokensAndSecrets[response.Token] = response.TokenSecret;
 }
 /// <summary>
 /// Stores a newly generated unauthorized request token, secret, and optional
 /// application-specific parameters for later recall.
 /// </summary>
 /// <param name="request">The request message that resulted in the generation of a new unauthorized request token.</param>
 /// <param name="response">The response message that includes the unauthorized request token.</param>
 /// <exception cref="T:System.ArgumentException">Thrown if the consumer key is not registered, or a required parameter was not found in the parameters collection.</exception>
 public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
 {
     this.requestToken       = response.Token;
     this.requestTokenSecret = response.TokenSecret;
 }
示例#31
0
 public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
 {
     // No-op
 }