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);
        }
Esempio n. 2
0
        /*
         * Start with an HttpRequest.
         * Throw if there are any attacks in the query.
         * Throw if there are any attacks in the post body.
         * Build up OAuth parameter list
         * Sign it.
         * Add OAuth parameters to new request
         * Send it.
         */
        public sRequest sanitizeAndSign(sRequest basereq, List <OAuth.Parameter> parameters)
        {
            if (parameters == null)
            {
                parameters = new List <OAuth.Parameter>();
            }
            UriBuilder target = new UriBuilder(basereq.getUri());
            String     query  = target.getQuery();

            target.setQuery(null);
            parameters.AddRange(sanitize(OAuth.decodeForm(query)));
            if (OAuth.isFormEncoded(basereq.ContentType))
            {
                parameters.AddRange(sanitize(OAuth.decodeForm(basereq.getPostBodyAsString())));
            }

            addIdentityParams(parameters);

            addSignatureParams(parameters);

            try
            {
                OAuthMessage signed = accessorInfo.getAccessor().newRequestMessage(
                    basereq.getMethod(), target.ToString(), parameters);
                sRequest oauthHttpRequest = createHttpRequest(basereq, selectOAuthParams(signed));
                // Following 302s on OAuth responses is unlikely to be productive.
                oauthHttpRequest.FollowRedirects = false;
                return(oauthHttpRequest);
            }
            catch (Exception e)
            {
                throw responseParams.oauthRequestException(OAuthError.UNKNOWN_PROBLEM,
                                                           "Error signing message", e);
            }
        }
        public OAuthProtocolException(OAuthMessage reply)
        {
            String problem = reply.getParameter(OAuthProblemException.OAUTH_PROBLEM);

            if (problem == null)
            {
                throw new ArgumentException(
                          "No problem reported for OAuthProtocolException");
            }
            problemCode = problem;
            if (fatalProblems.Contains(problem))
            {
                startFromScratch = true;
                canRetry         = false;
                canExtend        = false;
            }
            else if (temporaryProblems.Contains(problem))
            {
                startFromScratch = false;
                canRetry         = false;
                canExtend        = false;
            }
            else if (extensionProblems.Contains(problem))
            {
                startFromScratch = false;
                canRetry         = true;
                canExtend        = true;
            }
            else
            {
                startFromScratch = true;
                canRetry         = true;
                canExtend        = false;
            }
        }
        public bool thirdPartyHasAccessToUser(OAuthMessage message, String appUrl, String userId)
        {
            String appId = getAppId(appUrl);

            return(hasValidSignature(message, appUrl, appId) &&
                   userHasAppInstalled(userId, appId));
        }
Esempio n. 5
0
        public static List <OAuth.Parameter> getParameters(HttpRequest request)
        {
            List <OAuth.Parameter> list = new List <OAuth.Parameter>();

            foreach (String header in request.Headers.GetValues("Authorization"))
            {
                foreach (OAuth.Parameter parameter in OAuthMessage.decodeAuthorization(header))
                {
                    if (!parameter.Key.ToLower().Equals("realm"))
                    {
                        list.Add(parameter);
                    }
                }
            }
            for (int i = 0; i < request.QueryString.Count; i++)
            {
                String name = request.QueryString.GetKey(i);
                foreach (String value in request.QueryString.GetValues(i))
                {
                    list.Add(new OAuth.Parameter(name, value));
                }
            }
            for (int i = 0; i < request.Form.Count; i++)
            {
                String name = request.Form.GetKey(i);
                foreach (String value in request.Form.GetValues(i))
                {
                    list.Add(new OAuth.Parameter(name, value));
                }
            }
            return(list);
        }
        protected String getSignature(OAuthMessage message)
        {
            String baseString = getBaseString(message);
            String signature  = getSignature(baseString);

            return(signature);
        }
Esempio n. 7
0
        public override ISecurityToken getSecurityTokenFromRequest(HttpRequest request)
        {
            OAuthMessage requestMessage = OAuthServlet.getMessage(request, null);

            String containerKey       = getParameter(requestMessage, OAuth.OAUTH_CONSUMER_KEY);
            String containerSignature = getParameter(requestMessage, OAuth.OAUTH_SIGNATURE);
            String userId             = request.Params[REQUESTOR_ID_PARAM].Trim();

            if (containerKey == null || containerSignature == null || string.IsNullOrEmpty(userId))
            {
                // This isn't a proper OAuth request
                return(null);
            }

            try
            {
                if (service.thirdPartyHasAccessToUser(requestMessage, containerKey, userId))
                {
                    return(service.getSecurityToken(containerKey, userId));
                }
                throw new InvalidAuthenticationException("Access for app not allowed", null);
            }
            catch (OAuthException oae)
            {
                throw new InvalidAuthenticationException(oae.Message, oae);
            }
        }
        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);
        }
Esempio n. 9
0
        /// <summary>
        /// Builds the model. Override this to add information about the application requesting user consent, such as publisher information or a logo URL.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns>Returns the model.</returns>
        protected virtual AuthorizationServerViewModel BuildModel(OAuthMessage message)
        {
            var model = new AuthorizationServerViewModel();

            var applicationRegistration = ApplicationRegistrationService.GetApplication(message.Parameters["client_id"]);

            model.ApplicationName = applicationRegistration.ApplicationName;
            model.ApplicationUrl  = applicationRegistration.ApplicationUrl;

            return(model);
        }
Esempio n. 10
0
 private String getParameter(OAuthMessage requestMessage, String key)
 {
     try
     {
         return(requestMessage.getParameter(key));
     }
     catch
     {
         return(null);
     }
 }
Esempio n. 11
0
        /**
         * Extracts only those parameters from an OAuthMessage that are OAuth-related.
         * An OAuthMessage may hold a whole bunch of non-OAuth-related parameters
         * because they were all needed for signing. But when constructing a request
         * we need to be able to extract just the OAuth-related parameters because
         * they, and only they, may have to be put into an Authorization: header or
         * some such thing.
         *
         * @param message the OAuthMessage object, which holds non-OAuth parameters
         * such as foo=bar (which may have been in the original URI query part, or
         * perhaps in the POST body), as well as OAuth-related parameters (such as
         * oauth_timestamp or oauth_signature).
         *
         * @return a list that contains only the oauth_related parameters.
         *
         * @throws IOException
         */
        private static List <OAuth.Parameter> selectOAuthParams(OAuthMessage message)
        {
            List <OAuth.Parameter> result = new List <OAuth.Parameter>();

            foreach (var param in OAuthUtil.getParameters(message))
            {
                if (isContainerInjectedParameter(param.Key))
                {
                    result.Add(param);
                }
            }
            return(result);
        }
Esempio n. 12
0
        /// <summary>
        /// Checks if the client_id and the redirect_uri are valid.
        /// </summary>
        /// <param name="message">The message which contains the client_id and redirect_uri.</param>
        /// <param name="errorCode">The error code.</param>
        /// <param name="errorDescription">Description of the error.</param>
        /// <returns>
        /// True if the client_id and the redirect_uri are valid, false otherwise
        /// </returns>
        public bool ValidateServiceIdentity(OAuthMessage message, out string errorCode, out string errorDescription)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            string clientId    = message.Parameters[OAuthConstants.ClientId];
            string redirectUri = message.Parameters[OAuthConstants.RedirectUri];

            if (clientId == null || redirectUri == null)
            {
                errorCode        = OAuthConstants.ErrorCode.InvalidRequest;
                errorDescription = Resources.ID3716;
                return(false);
            }

            // Verify the client_id and redirect_uri with Windows Azure ACS
            try
            {
                var client = CreateManagementServiceClient();

                var serviceIdentity = client.ServiceIdentities.Where(si => si.Name == clientId).ToList().FirstOrDefault();
                if (serviceIdentity != null)
                {
                    if (serviceIdentity.RedirectAddress == redirectUri)
                    {
                        errorCode        = "";
                        errorDescription = "";
                        return(true);
                    }
                    else
                    {
                        errorCode        = OAuthConstants.ErrorCode.InvalidClient;
                        errorDescription = Resources.ID3750;
                    }
                }
                else
                {
                    errorCode        = OAuthConstants.ErrorCode.InvalidClient;
                    errorDescription = Resources.ID3751;
                }
            }
            catch (Exception)
            {
                errorCode        = OAuthConstants.ErrorCode.InvalidClient;
                errorDescription = Resources.ID3751;
            }

            return(false);
        }
Esempio n. 13
0
 /**
  * Look for an OAuth protocol problem.  For cases where no access token is in play
  * @param response
  * @throws OAuthProtocolException
  * @throws IOException
  */
 private void checkForProtocolProblem(sResponse response)
 {
     if (isFullOAuthError(response))
     {
         OAuthMessage message = parseAuthHeader(null, response);
         if (message.getParameter(OAuthProblemException.OAUTH_PROBLEM) != null)
         {
             // SP reported extended error information
             throw new OAuthProtocolException(message);
         }
         // No extended information, guess based on HTTP response code.
         throw new OAuthProtocolException(response.getHttpStatusCode());
     }
 }
Esempio n. 14
0
        /**
         * Parse OAuth WWW-Authenticate header and either add them to an existing
         * message or create a new message.
         *
         * @param msg
         * @param resp
         * @return the updated message.
         */
        private static OAuthMessage parseAuthHeader(OAuthMessage msg, sResponse resp)
        {
            if (msg == null)
            {
                msg = new OAuthMessage(null, null, null);
            }

            foreach (String auth in resp.getHeaders("WWW-Authenticate"))
            {
                msg.addParameters(OAuthMessage.decodeAuthorization(auth));
            }

            return(msg);
        }
Esempio n. 15
0
        /// <summary>
        /// This method validates the incoming request.
        /// </summary>
        /// <param name="message">The incoming reequest  message.</param>
        /// <param name="errorCode">The error code.</param>
        /// <param name="errorDescription">Description of the error.</param>
        /// <returns>
        /// True if request is valid, false otherwise.
        /// </returns>
        public bool ValidateIncomingRequest(OAuthMessage message, out string errorCode, out string errorDescription)
        {
            try
            {
                message.Validate();
            }
            catch (OAuthMessageException messageException)
            {
                errorCode        = OAuthConstants.ErrorCode.InvalidRequest;
                errorDescription = messageException.Message;
                return(false);
            }

            // Verify the client_id and redirect_uri
            return(ValidateServiceIdentity(message, out errorCode, out errorDescription));
        }
Esempio n. 16
0
 /**
  * Check whether the message has a valid signature.
  * @throws URISyntaxException 
  *
  * @throws OAuthProblemException
  *             the signature is invalid
  */
 public void validate(OAuthMessage message)
 {
     message.requireParameters(new[] { "oauth_signature" });
     String signature = message.getSignature();
     String baseString = getBaseString(message);
     if (!isValid(signature, baseString))
     {
         OAuthProblemException problem = new OAuthProblemException(
             "signature_invalid");
         problem.setParameter("oauth_signature", signature);
         problem.setParameter("oauth_signature_base_string", baseString);
         problem.setParameter("oauth_signature_method", message
                                                            .getSignatureMethod());
         throw problem;
     }
 }
Esempio n. 17
0
        /**
         * Check whether the message has a valid signature.
         * @throws URISyntaxException
         *
         * @throws OAuthProblemException
         *             the signature is invalid
         */
        public void validate(OAuthMessage message)
        {
            message.requireParameters(new[] { "oauth_signature" });
            String signature  = message.getSignature();
            String baseString = getBaseString(message);

            if (!isValid(signature, baseString))
            {
                OAuthProblemException problem = new OAuthProblemException(
                    "signature_invalid");
                problem.setParameter("oauth_signature", signature);
                problem.setParameter("oauth_signature_base_string", baseString);
                problem.setParameter("oauth_signature_method", message
                                     .getSignatureMethod());
                throw problem;
            }
        }
Esempio n. 18
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);
        }
    /**
     * 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
                    }));
                }
            }
        }
    }
Esempio n. 20
0
        /**
         * Sends OAuth request token and access token messages.
         * @throws GadgetException
         * @throws IOException
         * @throws OAuthProtocolException
         */
        private OAuthMessage sendOAuthMessage(sRequest request)
        {
            sResponse response = fetchFromServer(request);

            checkForProtocolProblem(response);
            OAuthMessage reply = new OAuthMessage(null, null, null);

            reply.addParameters(OAuth.decodeForm(response.responseString));
            reply = parseAuthHeader(reply, response);
            if (OAuthUtil.getParameter(reply, OAuth.OAUTH_TOKEN) == null)
            {
                throw responseParams.oauthRequestException(OAuthError.UNKNOWN_PROBLEM,
                                                           "No oauthToken returned from service provider");
            }
            if (OAuthUtil.getParameter(reply, OAuth.OAUTH_TOKEN_SECRET) == null)
            {
                throw responseParams.oauthRequestException(OAuthError.UNKNOWN_PROBLEM,
                                                           "No oauthToken_secret returned from service provider");
            }
            return(reply);
        }
Esempio n. 21
0
        public static String getBaseString(OAuthMessage message)
        {
            List <OAuth.Parameter> parameters;
            String url = message.URL;
            int    q   = url.IndexOf('?');

            if (q < 0)
            {
                parameters = message.getParameters();
            }
            else
            {
                // Combine the URL query string with the other parameters:
                parameters = new List <OAuth.Parameter>();
                parameters.AddRange(OAuth.decodeForm(url.Substring(q + 1)));
                parameters.AddRange(message.getParameters());
                url = url.Substring(0, q);
            }
            return(Rfc3986.Encode(message.method.ToUpper()) + '&'
                   + Rfc3986.Encode(normalizeUrl(url)) + '&'
                   + Rfc3986.Encode(normalizeParameters(parameters)));
        }
Esempio n. 22
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);
    }
        public virtual void Write(OAuthMessage message, HttpContextBase context)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            context.Response.ContentType = this.GetHttpContentType(message);
            context.Response.Clear();
            this.Write(message, context.Response.OutputStream);
            context.Response.Flush();
        }
Esempio n. 24
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;
 }
Esempio n. 25
0
 /** Add a signature to the message. 
  * @throws URISyntaxException 
  * @throws IOException */
 public void sign(OAuthMessage message)
 {
     message.addParameter(new OAuth.Parameter("oauth_signature", getSignature(message)));
 }
Esempio n. 26
0
 protected String getSignature(OAuthMessage message)
 {
     String baseString = getBaseString(message);
     String signature = getSignature(baseString);
     return signature;
 }
        /// <summary>
        /// This method validates the incoming request.
        /// </summary>
        /// <param name="message">The incoming reequest  message.</param>
        /// <param name="errorCode">The error code.</param>
        /// <param name="errorDescription">Description of the error.</param>
        /// <returns>
        /// True if request is valid, false otherwise.
        /// </returns>
        public bool ValidateIncomingRequest(OAuthMessage message, out string errorCode, out string errorDescription)
        {
            try
            {
                message.Validate();
            }
            catch (OAuthMessageException messageException)
            {
                errorCode = OAuthConstants.ErrorCode.InvalidRequest;
                errorDescription = messageException.Message;
                return false;
            }

            // Verify the client_id and redirect_uri
            return ValidateServiceIdentity(message, out errorCode, out errorDescription);
        }
        public virtual string GetJsonEncodedFormat(OAuthMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            var serializedMessage = JsonConvert.SerializeObject(message.Parameters);

            // TODO: replace token of array to object...
            return serializedMessage;
        }
        public virtual string GetQueryStringFormat(OAuthMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
            strBuilder.Append(message.BaseUri.AbsoluteUri);
            strBuilder.Append("?");
            strBuilder.Append(this.GetFormEncodedQueryFormat(message));
            return strBuilder.ToString();
        }
Esempio n. 30
0
 public static List <OAuth.Parameter> getParameters(OAuthMessage message)
 {
     return(message.getParameters());
 }
Esempio n. 31
0
 public static void requireParameters(OAuthMessage message, string[] names)
 {
     message.requireParameters(names);
 }
Esempio n. 32
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);
                    }
                }
            }
        }
Esempio n. 33
0
 public static String getBaseString(OAuthMessage message)
 {
     List<OAuth.Parameter> parameters;
     String url = message.URL;
     int q = url.IndexOf('?');
     if (q < 0)
     {
         parameters = message.getParameters();
     }
     else
     {
         // Combine the URL query string with the other parameters:
         parameters = new List<OAuth.Parameter>();
         parameters.AddRange(OAuth.decodeForm(url.Substring(q + 1)));
         parameters.AddRange(message.getParameters());
         url = url.Substring(0, q);
     }
     return Rfc3986.Encode(message.method.ToUpper()) + '&'
            + Rfc3986.Encode(normalizeUrl(url)) + '&'
            + Rfc3986.Encode(normalizeParameters(parameters));
 }
        public virtual string GetHttpContentType(OAuthMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            AccessTokenRequest atRequestMessage = message as AccessTokenRequest;
            if (atRequestMessage != null)
            {
                return "application/x-www-form-urlencoded";
            }

            AccessTokenResponse atResponseMessage = message as AccessTokenResponse;
            if (atResponseMessage != null)
            {
                return "application/json";
            }
            return "text/plain; charset=us-ascii";
        }
        public virtual void Write(OAuthMessage message, HttpWebRequest request)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            request.Method = this.GetHttpMethod(message);
            request.ContentType = this.GetHttpContentType(message);
            this.Write(message, request.GetRequestStream());
        }
        public virtual void Write(OAuthMessage message, System.IO.Stream requestStream)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            if (requestStream == null)
            {
                throw new ArgumentNullException("requestStream");
            }

            System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(requestStream);
            AccessTokenRequest atRequestMsg = message as AccessTokenRequest;
            if (atRequestMsg != null)
            {
                streamWriter.Write(this.GetFormEncodedQueryFormat(message));
                streamWriter.Flush();
                return;
            }

            AccessTokenResponse atResponseMsg = message as AccessTokenResponse;
            if (atResponseMsg != null)
            {
                streamWriter.Write(this.GetJsonEncodedFormat(message));
                streamWriter.Flush();
                return;
            }

            throw new OAuthMessageException(string.Format(Resources.ID3724, message.GetType()));
        }
Esempio n. 37
0
 public static String getParameter(OAuthMessage message, String name)
 {
     return(message.getParameter(name));
 }
 public virtual string GetFormEncodedQueryFormat(OAuthMessage message)
 {
     if (message == null)
     {
         throw new ArgumentNullException("message");
     }
     System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
     bool skipDelimiter = true;
     foreach (string key in message.Parameters.Keys)
     {
         if (message.Parameters[key] != null)
         {
             if (!skipDelimiter)
             {
                 strBuilder.Append("&");
             }
             strBuilder.Append(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}={1}", new object[]
                                                                                                               {
                                                                                                                   HttpUtility.UrlEncode(key), 
                                                                                                                   HttpUtility.UrlEncode(message.Parameters[key])
                                                                                                               }));
             skipDelimiter = false;
         }
     }
     return strBuilder.ToString();
 }
Esempio n. 39
0
 /** Add a signature to the message.
  * @throws URISyntaxException
  * @throws IOException */
 public void sign(OAuthMessage message)
 {
     message.addParameter(new OAuth.Parameter("oauth_signature", getSignature(message)));
 }
        public virtual string GetHttpMethod(OAuthMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            AccessTokenRequest atRequestMessage = message as AccessTokenRequest;
            if (atRequestMessage != null)
            {
                return "POST";
            }

            AccessTokenResponse atResponseMessage = message as AccessTokenResponse;
            if (atResponseMessage != null)
            {
                return "POST";
            }

            return "GET";
        }
        /// <summary>
        /// Checks if the client_id and the redirect_uri are valid.
        /// </summary>
        /// <param name="message">The message which contains the client_id and redirect_uri.</param>
        /// <param name="errorCode">The error code.</param>
        /// <param name="errorDescription">Description of the error.</param>
        /// <returns>
        /// True if the client_id and the redirect_uri are valid, false otherwise
        /// </returns>
        public bool ValidateServiceIdentity(OAuthMessage message, out string errorCode, out string errorDescription)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            string clientId = message.Parameters[OAuthConstants.ClientId];
            string redirectUri = message.Parameters[OAuthConstants.RedirectUri];

            if (clientId == null || redirectUri == null)
            {
                errorCode = OAuthConstants.ErrorCode.InvalidRequest;
                errorDescription = Resources.ID3716;
                return false;
            }

            // Verify the client_id and redirect_uri with Windows Azure ACS
            try
            {
                var client = CreateManagementServiceClient();

                var serviceIdentity = client.ServiceIdentities.Where(si => si.Name == clientId).ToList().FirstOrDefault();
                if (serviceIdentity != null)
                {
                    if (serviceIdentity.RedirectAddress == redirectUri)
                    {
                        errorCode = "";
                        errorDescription = "";
                        return true;
                    }
                    else
                    {
                        errorCode = OAuthConstants.ErrorCode.InvalidClient;
                        errorDescription = Resources.ID3750;
                    }
                }
                else
                {
                    errorCode = OAuthConstants.ErrorCode.InvalidClient;
                    errorDescription = Resources.ID3751;
                }
            }
            catch (Exception)
            {
                errorCode = OAuthConstants.ErrorCode.InvalidClient;
                errorDescription = Resources.ID3751;
            }

            return false;
        }
Esempio n. 42
0
        private Status GenerateSuggestions(WorkflowInstance workflowInstance, ServerEntity entity, Dictionary <string, string> suggestionList)
        {
            Item item = entity as Item;

            if (item == null)
            {
                TraceLog.TraceError("Entity is not an Item");
                return(Status.Error);
            }

            User user = UserContext.GetUser(item.UserID, true);

            if (user == null)
            {
                TraceLog.TraceError("Could not find the user associated with Item " + item.Name);
                return(Status.Error);
            }

            ADGraphAPI adApi          = new ADGraphAPI();
            string     adRefreshToken = null;

            // check for FB and/or AD credentials
            UserCredential cred = user.GetCredential(UserCredential.FacebookConsent);

            if (cred != null && cred.AccessToken != null)
            {
                adApi.FacebookAccessToken = cred.AccessToken;
            }
            cred = user.GetCredential(UserCredential.CloudADConsent);
            if (cred != null && cred.RenewalToken != null)
            {
                adRefreshToken = cred.RenewalToken;
            }

            if (adApi.FacebookAccessToken == null && adRefreshToken == null)
            {   // user not having either token is not an error condition, but there is no way to generate suggestions
                // just move forward from this state
                return(Status.Complete);
            }

            // if a refresh token exists for AD, get an access token from Azure ACS for the Azure AD service
            if (adRefreshToken != null)
            {
                try
                {
                    AccessTokenRequestWithRefreshToken request = new AccessTokenRequestWithRefreshToken(new Uri(AzureOAuthConfiguration.GetTokenUri()))
                    {
                        RefreshToken = adRefreshToken,
                        ClientId     = AzureOAuthConfiguration.GetClientIdentity(),
                        ClientSecret = AzureOAuthConfiguration.ClientSecret,
                        Scope        = AzureOAuthConfiguration.RelyingPartyRealm,
                    };
                    OAuthMessage        message       = OAuthClient.GetAccessToken(request);
                    AccessTokenResponse authzResponse = message as AccessTokenResponse;
                    adApi.ADAccessToken = authzResponse.AccessToken;

                    // workaround for ACS trashing the refresh token
                    if (!String.IsNullOrEmpty(authzResponse.RefreshToken))
                    {
                        TraceLog.TraceInfo("Storing new CloudAD refresh token");
                        user.AddCredential(UserCredential.CloudADConsent, authzResponse.AccessToken, null, authzResponse.RefreshToken);
                        UserContext.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    TraceLog.TraceException("Could not contact ACS to get an access token", ex);

                    // Facebook credentials are not available
                    if (adApi.FacebookAccessToken == null)
                    {
                        return(Status.Pending);  // could be a temporary outage, do not move off this state
                    }
                }
            }

            // extract a subject hint if one hasn't been discovered yet
            string subjectHint = GetInstanceData(workflowInstance, ActivityVariables.SubjectHint);

            if (String.IsNullOrEmpty(subjectHint))
            {
                try
                {
                    Phrase phrase = new Phrase(item.Name);
                    if (phrase.Task != null)
                    {
                        subjectHint = phrase.Task.Subject;
                        if (!String.IsNullOrWhiteSpace(subjectHint))
                        {
                            StoreInstanceData(workflowInstance, ActivityVariables.SubjectHint, subjectHint);
                        }
                    }
                }
                catch (Exception ex)
                {
                    TraceLog.TraceException("Could not initialize NLP engine", ex);
                }
            }

            // get contacts from Cloud AD and Facebook via the AD Graph Person service
            // TODO: also get local contacts from the Contacts folder
            try
            {
                var results = adApi.Query(subjectHint ?? "");
                foreach (var subject in results)
                {
                    // serialize an existing contact corresponding to the subject,
                    // or generate a new serialized contact if one wasn't found
                    Item contact = MakeContact(workflowInstance, item, subject);
                    suggestionList[contact.Name] = JsonSerializer.Serialize(contact);
                }
            }
            catch (Exception ex)
            {
                TraceLog.TraceException("Could not contact Person Service", ex);
                return(Status.Error);
            }

            // inexact match
            return(Status.Pending);
        }
        /// <summary>
        /// Builds the model. Override this to add information about the application requesting user consent, such as publisher information or a logo URL.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns>Returns the model.</returns>
        protected virtual AuthorizationServerViewModel BuildModel(OAuthMessage message)
        {
            var model = new AuthorizationServerViewModel();

            var applicationRegistration = ApplicationRegistrationService.GetApplication(message.Parameters["client_id"]);

            model.ApplicationName = applicationRegistration.ApplicationName;
            model.ApplicationUrl = applicationRegistration.ApplicationUrl;

            return model;
        }