/** The factory for signature methods. */
 public static OAuthSignatureMethod newMethod(String name,
                                              OAuthAccessor accessor)
 {
     try
     {
         Type methodClass = NAME_TO_CLASS[name];
         if (methodClass != null)
         {
             OAuthSignatureMethod method = (OAuthSignatureMethod)Activator.CreateInstance(methodClass);
             method.initialize(name, accessor);
             return(method);
         }
         OAuthProblemException problem = new OAuthProblemException("signature_method_rejected");
         List <string>         todo    = new List <string>();
         foreach (var item in NAME_TO_CLASS.Keys)
         {
             todo.Add(item);
         }
         String acceptable = OAuth.percentEncode(todo);
         if (acceptable.Length > 0)
         {
             problem.setParameter("oauth_acceptable_signature_methods",
                                  acceptable);
         }
         throw problem;
     }
     catch (Exception e)
     {
         throw new OAuthException(e);
     }
 }
        private static bool hasValidSignature(OAuthMessage message, String appUrl, String appId)
        {
            String sharedSecret = sampleContainerSharedSecrets[appId];

            if (sharedSecret == null)
            {
                return(false);
            }

            OAuthServiceProvider provider = new OAuthServiceProvider(null, null, null);
            OAuthConsumer        consumer = new OAuthConsumer(null, appUrl, sharedSecret, provider);
            OAuthAccessor        accessor = new OAuthAccessor(consumer);

            SimpleOAuthValidator validator = new SimpleOAuthValidator();

            try
            {
                validator.validateMessage(message, accessor);
            }
            catch (OAuthException)
            {
                return(false);
            }
            catch (IOException)
            {
                return(false);
            }
            catch (UriFormatException)
            {
                return(false);
            }

            return(true);
        }
Beispiel #3
0
        /**
         * Builds the data we'll cache on the client while we wait for approval.
         */
        private void buildClientApprovalState()
        {
            OAuthAccessor accessor = accessorInfo.getAccessor();

            responseParams.getNewClientState().setRequestToken(accessor.requestToken);
            responseParams.getNewClientState().setRequestTokenSecret(accessor.TokenSecret);
            responseParams.getNewClientState().setOwner(realRequest.getSecurityToken().getOwnerId());
        }
Beispiel #4
0
        /**
         * Save off our new token and secret to the persistent store.
         *
         * @throws GadgetException
         */
        private void saveAccessToken()
        {
            OAuthAccessor accessor = accessorInfo.getAccessor();

            OAuthStore.TokenInfo tokenInfo = new OAuthStore.TokenInfo(accessor.accessToken, accessor.TokenSecret,
                                                                      accessorInfo.getSessionHandle(), accessorInfo.getTokenExpireMillis());
            fetcherConfig.getTokenStore().storeTokenKeyAndSecret(realRequest.getSecurityToken(),
                                                                 accessorInfo.getConsumer(), realRequest.getOAuthArguments(), tokenInfo, responseParams);
        }
Beispiel #5
0
        /**
         * Builds the data we'll cache on the client while we make requests.
         */
        private void buildClientAccessState()
        {
            OAuthAccessor accessor = accessorInfo.getAccessor();

            responseParams.getNewClientState().setAccessToken(accessor.accessToken);
            responseParams.getNewClientState().setAccessTokenSecret(accessor.TokenSecret);
            responseParams.getNewClientState().setOwner(realRequest.getSecurityToken().getOwnerId());
            responseParams.getNewClientState().setSessionHandle(accessorInfo.getSessionHandle());
            responseParams.getNewClientState().setTokenExpireMillis(accessorInfo.getTokenExpireMillis());
        }
        public static OAuthSignatureMethod newSigner(OAuthMessage message,
                                                     OAuthAccessor accessor)
        {
            message.requireParameters(new[] { OAuth.OAUTH_SIGNATURE_METHOD });
            OAuthSignatureMethod signer = newMethod(message.getSignatureMethod(),
                                                    accessor);

            signer.setTokenSecret(accessor.TokenSecret);
            return(signer);
        }
Beispiel #7
0
        protected override void initialize(string name, OAuthAccessor accessor)
        {
            base.initialize(name, accessor);
            // get pass
            string pass = accessor.consumer.getProperty(X509_CERTIFICATE_PASS) as string;
            // get certificate location
            string certloc = accessor.consumer.getProperty(X509_CERTIFICATE) as string;

            certificate = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + certloc, pass);
        }
Beispiel #8
0
 public AccessorInfo(OAuthAccessor accessor, OAuthStore.ConsumerInfo consumer, HttpMethod httpMethod,
                     OAuthParamLocation?paramLocation, String sessionHandle, long tokenExpireMillis)
 {
     this.accessor          = accessor;
     this.consumer          = consumer;
     this.httpMethod        = httpMethod;
     this.paramLocation     = paramLocation;
     this.sessionHandle     = sessionHandle;
     this.tokenExpireMillis = tokenExpireMillis;
 }
Beispiel #9
0
        protected override void initialize(string name, OAuthAccessor accessor)
        {
            base.initialize(name, accessor);
            // get pass
            string pass = accessor.consumer.getProperty(X509_CERTIFICATE_PASS) as string;
            // get certificate location
            string certloc = accessor.consumer.getProperty(X509_CERTIFICATE) as string;

            certificate = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + certloc, pass);
        } 
Beispiel #10
0
        private void fetchRequestToken()
        {
            OAuthAccessor accessor = accessorInfo.getAccessor();
            sRequest      request  = new sRequest(Uri.parse(accessor.consumer.serviceProvider.requestTokenURL));

            request.setMethod(accessorInfo.getHttpMethod().ToString());
            if (accessorInfo.getHttpMethod().CompareTo(AccessorInfo.HttpMethod.POST) == 0)
            {
                request.setContentType(OAuth.FORM_ENCODED);
            }

            sRequest signed = sanitizeAndSign(request, null);

            OAuthMessage reply = sendOAuthMessage(signed);

            accessor.requestToken = reply.getParameter(OAuth.OAUTH_TOKEN);
            accessor.TokenSecret  = reply.getParameter(OAuth.OAUTH_TOKEN_SECRET);
        }
Beispiel #11
0
 protected virtual void initialize(String name, OAuthAccessor accessor)
 {
     String secret = accessor.consumer.consumerSecret;
     if (name.EndsWith(_ACCESSOR))
     {
         // This code supports the 'Accessor Secret' extensions
         // described in http://oauth.pbwiki.com/AccessorSecret
         String key = OAuthConsumer.ACCESSOR_SECRET;
         Object accessorSecret = accessor.getProperty(key) ?? accessor.consumer.getProperty(key);
         if (accessorSecret != null)
         {
             secret = accessorSecret.ToString();
         }
     }
     if (secret == null)
     {
         secret = "";
     }
     setConsumerSecret(secret);
 }
Beispiel #12
0
        public AccessorInfo create(OAuthResponseParams responseParams)
        {
            if (location == null)
            {
                throw responseParams.oauthRequestException(OAuthError.UNKNOWN_PROBLEM, "no location");
            }
            if (consumer == null)
            {
                throw responseParams.oauthRequestException(OAuthError.UNKNOWN_PROBLEM, "no consumer");
            }

            OAuthAccessor accessor = new OAuthAccessor(consumer.getConsumer());

            // request token/access token/token secret can all be null, for signed fetch, or if the OAuth
            // dance is just beginning
            accessor.requestToken = requestToken;
            accessor.accessToken  = accessToken;
            accessor.TokenSecret  = tokenSecret;
            return(new AccessorInfo(accessor, consumer, method, location, sessionHandle, tokenExpireMillis));
        }
    /**
     * Signs the URL associated with the passed request object using the passed
     * consumer key and secret in accordance with the OAuth specification and
     * appends signature and other required parameters to the URL as query
     * string parameters.
     *
     * @param  request OpenSocialHttpRequest object which contains both the URL
     *         to sign as well as the POST body which must be included as a
     *         parameter when signing POST requests
     * @param  consumerKey Application key assigned and used by containers to
     *         uniquely identify applications
     * @param  consumerSecret Secret key shared between application owner and
     *         container. Used to generate the signature which is attached to
     *         the request so containers can verify the authenticity of the
     *         requests made by the client application.
     * @throws OAuthException
     * @throws IOException
     * @throws URISyntaxException
     */
    public static void signRequest(
        OpenSocialHttpRequest request, String consumerKey, String consumerSecret)
    {
        String        postBody      = request.getPostBody();
        String        requestMethod = request.getMethod();
        OpenSocialUrl requestUrl    = request.getUrl();

        if (!String.IsNullOrEmpty(consumerKey) && !String.IsNullOrEmpty(consumerSecret))
        {
            OAuthMessage message =
                new OAuthMessage(requestMethod, requestUrl.ToString(), null);

            if (!String.IsNullOrEmpty(postBody))
            {
                message.addParameter(postBody, "");
            }

            OAuthConsumer consumer =
                new OAuthConsumer(null, consumerKey, consumerSecret, null);
            consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.HMAC_SHA1);

            OAuthAccessor accessor = new OAuthAccessor(consumer);
            accessor.accessToken = "";

            message.addRequiredParameters(accessor);

            foreach (var p in message.getParameters())
            {
                if (!p.Key.Equals(postBody))
                {
                    requestUrl.addQueryStringParameter(
                        OAuth.percentEncode(new List <string> {
                        p.Key
                    }),
                        OAuth.percentEncode(new List <string> {
                        p.Value
                    }));
                }
            }
        }
    }
        protected virtual void initialize(String name, OAuthAccessor accessor)
        {
            String secret = accessor.consumer.consumerSecret;

            if (name.EndsWith(_ACCESSOR))
            {
                // This code supports the 'Accessor Secret' extensions
                // described in http://oauth.pbwiki.com/AccessorSecret
                String key            = OAuthConsumer.ACCESSOR_SECRET;
                Object accessorSecret = accessor.getProperty(key) ?? accessor.consumer.getProperty(key);
                if (accessorSecret != null)
                {
                    secret = accessorSecret.ToString();
                }
            }
            if (secret == null)
            {
                secret = "";
            }
            setConsumerSecret(secret);
        }
Beispiel #15
0
        /**
         * Builds the URL the client needs to visit to approve access.
         */
        private void buildAznUrl()
        {
            // At some point we can be clever and use a callback URL to improve
            // the user experience, but that's too complex for now.
            OAuthAccessor accessor = accessorInfo.getAccessor();
            StringBuilder azn      = new StringBuilder(
                accessor.consumer.serviceProvider.userAuthorizationURL);

            if (azn.ToString().IndexOf("?") == -1)
            {
                azn.Append('?');
            }
            else
            {
                azn.Append('&');
            }
            azn.Append(OAuth.OAUTH_TOKEN);
            azn.Append('=');
            azn.Append(Rfc3986.Encode(accessor.requestToken));
            responseParams.setAznUrl(azn.ToString());
        }
Beispiel #16
0
    /**
     * Validates the passed request by reconstructing the original URL and
     * parameters and generating a signature following the OAuth HMAC-SHA1
     * specification and using the passed secret key.
     *
     * @param  request Servlet request containing required information for
     *         reconstructing the signature such as the request's URL
     *         components and parameters
     * @param  consumerSecret Secret key shared between application owner and
     *         container. Used by containers when issuing signed makeRequests
     *         and by client applications to verify the source of these
     *         requests and the authenticity of its parameters.
     * @return {@code true} if the signature generated in this function matches
     *         the signature in the passed request, {@code false} otherwise
     * @throws IOException
     * @throws URISyntaxException
     */
    public static bool verifyHmacSignature(
        HttpWebRequest request, String consumerSecret)
    {
        String method     = request.Method;
        String requestUrl = getRequestUrl(request);
        List <OAuth.Parameter> requestParameters = getRequestParameters(request);

        OAuthMessage message =
            new OAuthMessage(method, requestUrl, requestParameters);

        OAuthConsumer consumer =
            new OAuthConsumer(null, null, consumerSecret, null);
        OAuthAccessor accessor = new OAuthAccessor(consumer);

        try {
            message.validateMessage(accessor, new SimpleOAuthValidator());
        } catch (OAuthException e) {
            return(false);
        }

        return(true);
    }
Beispiel #17
0
 public static OAuthSignatureMethod newSigner(OAuthMessage message,
                                              OAuthAccessor accessor)
 {
     message.requireParameters(new[] { OAuth.OAUTH_SIGNATURE_METHOD });
     OAuthSignatureMethod signer = newMethod(message.getSignatureMethod(),
                                             accessor);
     signer.setTokenSecret(accessor.TokenSecret);
     return signer;
 }
Beispiel #18
0
 /** The factory for signature methods. */
 public static OAuthSignatureMethod newMethod(String name,
                                              OAuthAccessor accessor)
 {
     try
     {
         Type methodClass = NAME_TO_CLASS[name];
         if (methodClass != null)
         {
             OAuthSignatureMethod method = (OAuthSignatureMethod)Activator.CreateInstance(methodClass);
             method.initialize(name, accessor);
             return method;
         }
         OAuthProblemException problem = new OAuthProblemException("signature_method_rejected");
         List<string> todo = new List<string>();
         foreach (var item in NAME_TO_CLASS.Keys)
         {
             todo.Add(item);
         }
         String acceptable = OAuth.percentEncode(todo);
         if (acceptable.Length > 0)
         {
             problem.setParameter("oauth_acceptable_signature_methods",
                                  acceptable);
         }
         throw problem;
     }
     catch (Exception e)
     {
         throw new OAuthException(e);
     }
 }
Beispiel #19
0
        /**
         * Implements section 6.3 of the OAuth spec.
         * @throws OAuthProtocolException
         */
        private void exchangeRequestToken()
        {
            if (accessorInfo.getAccessor().accessToken != null)
            {
                // session extension per
                // http://oauth.googlecode.com/svn/spec/ext/session/1.0/drafts/1/spec.html
                accessorInfo.getAccessor().requestToken = accessorInfo.getAccessor().accessToken;
                accessorInfo.getAccessor().accessToken  = null;
            }
            OAuthAccessor accessor       = accessorInfo.getAccessor();
            Uri           accessTokenUri = Uri.parse(accessor.consumer.serviceProvider.accessTokenURL);
            sRequest      request        = new sRequest(accessTokenUri);

            request.setMethod(accessorInfo.getHttpMethod().ToString());
            if (accessorInfo.getHttpMethod() == AccessorInfo.HttpMethod.POST)
            {
                request.setContentType(OAuth.FORM_ENCODED);
            }

            List <OAuth.Parameter> msgParams = new List <OAuth.Parameter>
            {
                new OAuth.Parameter(OAuth.OAUTH_TOKEN, accessor.requestToken)
            };

            if (accessorInfo.getSessionHandle() != null)
            {
                msgParams.Add(new OAuth.Parameter(OAUTH_SESSION_HANDLE, accessorInfo.getSessionHandle()));
            }

            sRequest signed = sanitizeAndSign(request, msgParams);

            OAuthMessage reply = sendOAuthMessage(signed);

            accessor.accessToken = OAuthUtil.getParameter(reply, OAuth.OAUTH_TOKEN);
            accessor.TokenSecret = OAuthUtil.getParameter(reply, OAuth.OAUTH_TOKEN_SECRET);
            accessorInfo.setSessionHandle(OAuthUtil.getParameter(reply, OAUTH_SESSION_HANDLE));
            accessorInfo.setTokenExpireMillis(ACCESS_TOKEN_EXPIRE_UNKNOWN);
            if (OAuthUtil.getParameter(reply, OAUTH_EXPIRES_IN) != null)
            {
                try
                {
                    int  expireSecs   = int.Parse(OAuthUtil.getParameter(reply, OAUTH_EXPIRES_IN));
                    long expireMillis = DateTime.UtcNow.AddSeconds(expireSecs).Ticks;
                    accessorInfo.setTokenExpireMillis(expireMillis);
                }
                catch (FormatException)
                {
                    // Hrm.  Bogus server.  We can safely ignore this, we'll just wait for the server to
                    // tell us when the access token has expired.
                    responseParams.logDetailedWarning("server returned bogus expiration");
                }
            }

            // Clients may want to retrieve extra information returned with the access token.  Several
            // OAuth service providers (e.g. Yahoo, NetFlix) return a user id along with the access
            // token, and the user id is required to use their APIs.  Clients signal that they need this
            // extra data by sending a fetch request for the access token URL.
            //
            // We don't return oauth* parameters from the response, because we know how to handle those
            // ourselves and some of them (such as oauthToken_secret) aren't supposed to be sent to the
            // client.
            //
            // Note that this data is not stored server-side.  Clients need to cache these user-ids or
            // other data themselves, probably in user prefs, if they expect to need the data in the
            // future.
            if (accessTokenUri.Equals(realRequest.getUri()))
            {
                accessTokenData = new Dictionary <string, string>();
                foreach (var param in OAuthUtil.getParameters(reply))
                {
                    if (!param.Key.StartsWith("oauth"))
                    {
                        accessTokenData.Add(param.Key, param.Value);
                    }
                }
            }
        }
Beispiel #20
0
 public static OAuthMessage newRequestMessage(OAuthAccessor accessor, String method, String url,
                                              List <OAuth.Parameter> parameters)
 {
     return(accessor.newRequestMessage(method, url, parameters));
 }