Beispiel #1
0
    public OAuthParameters BuildProtectedResourceSignature(string method, WebPairCollection parameters, string url)
    {
        ValidateProtectedResourceState();

        var allParameters = new WebPairCollection();

        allParameters.AddRange(parameters);

        // Include url parameters in query pool
        var uri           = new Uri(url);
        var urlParameters = HttpUtility.ParseQueryString(uri.Query);

        allParameters.AddRange(urlParameters.AllKeys.Select(x => new WebPair(x !, urlParameters[x] !)));

        var timestamp = OAuthTools.GetTimestamp();
        var nonce     = OAuthTools.GetNonce();

        var authParameters = GenerateAuthParameters(timestamp, nonce);

        allParameters.AddRange(authParameters);

        var signatureBase = OAuthTools.ConcatenateRequestElements(method, url, allParameters);

        return(new OAuthParameters {
            Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret),
            Parameters = authParameters
        });
    }
Beispiel #2
0
    /// <summary>
    /// Generates an OAuth signature to pass to an
    /// <see cref="IAuthenticator" /> for the purpose of requesting an
    /// unauthorized request token.
    /// </summary>
    /// <param name="method">The HTTP method for the intended request</param>
    /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param>
    /// <returns></returns>
    public OAuthParameters BuildRequestTokenInfo(string method, WebPairCollection parameters)
    {
        ValidateTokenRequestState();

        var allParameters = new WebPairCollection();

        allParameters.AddRange(parameters);

        var timestamp = OAuthTools.GetTimestamp();
        var nonce     = OAuthTools.GetNonce();

        var authParameters = GenerateAuthParameters(timestamp, nonce);

        allParameters.AddRange(authParameters);

        var signatureBase = OAuthTools.ConcatenateRequestElements(method, Ensure.NotNull(RequestTokenUrl, nameof(RequestTokenUrl)), allParameters);

        return(new OAuthParameters {
            Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret),
            Parameters = authParameters
        });
    }
Beispiel #3
0
    /// <summary>
    /// Generates an OAuth signature to pass to an
    /// <see cref="IAuthenticator" /> for the purpose of exchanging user credentials
    /// for an access token authorized by the user at the Service Provider site.
    /// </summary>
    /// <param name="method">The HTTP method for the intended request</param>
    /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param>
    public OAuthParameters BuildClientAuthAccessTokenSignature(string method, WebPairCollection parameters)
    {
        ValidateClientAuthAccessRequestState();

        var allParameters = new WebPairCollection();

        allParameters.AddRange(parameters);

        var uri       = new Uri(Ensure.NotNull(AccessTokenUrl, nameof(AccessTokenUrl)));
        var timestamp = OAuthTools.GetTimestamp();
        var nonce     = OAuthTools.GetNonce();

        var authParameters = GenerateXAuthParameters(timestamp, nonce);

        allParameters.AddRange(authParameters);

        var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), allParameters);

        return(new OAuthParameters {
            Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret),
            Parameters = authParameters
        });
    }
        void AddOAuthData(IRestClient client, IRestRequest request, OAuthWorkflow workflow)
        {
            var requestUrl = client.BuildUriWithoutQueryParameters(request);

            if (requestUrl.Contains('?'))
            {
                throw new ApplicationException(
                          "Using query parameters in the base URL is not supported for OAuth calls. Consider using AddDefaultQueryParameter instead."
                          );
            }

            var url = client.BuildUri(request).ToString();
            var queryStringStart = url.IndexOf('?');

            if (queryStringStart != -1)
            {
                url = url.Substring(0, queryStringStart);
            }

            var method = request.Method.ToString().ToUpperInvariant();

            var parameters = new WebPairCollection();

            // include all GET and POST parameters before generating the signature
            // according to the RFC 5849 - The OAuth 1.0 Protocol
            // http://tools.ietf.org/html/rfc5849#section-3.4.1
            // if this change causes trouble we need to introduce a flag indicating the specific OAuth implementation level,
            // or implement a separate class for each OAuth version
            bool BaseQuery(Parameter x)
            => x.Type == ParameterType.GetOrPost || x.Type == ParameterType.QueryString || x.Type == ParameterType.QueryStringWithoutEncode;

            var query =
                request.AlwaysMultipartFormData || request.Files.Count > 0
                    ? x => BaseQuery(x) && x.Name.StartsWith("oauth_")
                    : (Func <Parameter, bool>)BaseQuery;

            parameters.AddRange(client.DefaultParameters.Where(query).ToWebParameters());
            parameters.AddRange(request.Parameters.Where(query).ToWebParameters());

            if (Type == OAuthType.RequestToken)
            {
                workflow.RequestTokenUrl = url;
            }
            else
            {
                workflow.AccessTokenUrl = url;
            }

            var oauth = Type switch
            {
                OAuthType.RequestToken => workflow.BuildRequestTokenInfo(method, parameters),
                OAuthType.AccessToken => workflow.BuildAccessTokenSignature(method, parameters),
                OAuthType.ClientAuthentication => workflow.BuildClientAuthAccessTokenSignature(method, parameters),
                OAuthType.ProtectedResource => workflow.BuildProtectedResourceSignature(method, parameters, url),
                _ => throw new ArgumentOutOfRangeException()
            };

            parameters.Add("oauth_signature", oauth);

            var oauthParameters = ParameterHandling switch
            {
                OAuthParameterHandling.HttpAuthorizationHeader => CreateHeaderParameters(),
                OAuthParameterHandling.UrlOrPostParameters => CreateUrlParameters(),
                _ =>
                throw new ArgumentOutOfRangeException()
            };

            request.AddOrUpdateParameters(oauthParameters);

            IEnumerable <Parameter> CreateHeaderParameters()
            => new[] { new Parameter("Authorization", GetAuthorizationHeader(parameters), ParameterType.HttpHeader) };

            IEnumerable <Parameter> CreateUrlParameters()
            => parameters.Where(p => !p.Name.IsNullOrBlank() && (p.Name.StartsWith("oauth_") || p.Name.StartsWith("x_auth_")))
            .Select(p => new Parameter(p.Name, HttpUtility.UrlDecode(p.Value), ParameterType.GetOrPost));
        }

        string GetAuthorizationHeader(WebPairCollection parameters)
        {
            var oathParameters =
                parameters
                .OrderBy(x => x, WebPair.Comparer)
                .Where(
                    p =>
                    !p.Name.IsNullOrBlank() && !p.Value.IsNullOrBlank() &&
                    (p.Name.StartsWith("oauth_") || p.Name.StartsWith("x_auth_"))
                    )
                .Select(x => $"{x.Name}=\"{x.Value}\"")
                .ToList();

            if (!Realm.IsNullOrBlank())
            {
                oathParameters.Insert(0, $"realm=\"{OAuthTools.UrlEncodeRelaxed(Realm)}\"");
            }

            return("OAuth " + string.Join(",", oathParameters));
        }
    }