public void Test_SignatureCompareWithSpaceInSignature() { OAuthParameters parameters = new OAuthParameters() { ConsumerKey = "key", Nonce = "5b434e59-729a-444b-9a11-2d8e57b1f2fb", SignatureMethod = "HMAC-SHA1", Timestamp = "1251983826", Version = "1.0", Callback = "http://yourownsite.com/" }; string sigbase = SignatureBase.Create( "GET", new Uri("http://localhost:3423/request-token.ashx"), parameters); string consumerSecret = "secret"; string tokenSecret = null; HmacSha1SigningProvider signingProvider = new HmacSha1SigningProvider(); Assert.That(signingProvider.SignatureMethod, Is.EqualTo("HMAC-SHA1")); string hash = signingProvider.ComputeSignature(sigbase, consumerSecret, tokenSecret); Assert.That(hash, Is.EqualTo("zHTiQHg8X5Lpkh+/0MSatKeNEFg=")); Assert.That(signingProvider.CheckSignature(sigbase, Rfc3986.Decode("zHTiQHg8X5Lpkh+/0MSatKeNEFg="), consumerSecret, tokenSecret), "Signature did not match"); }
public bool ValidateSignature(string signatureBase, string signature, string consumerSecret, string tokenSecret) { string expectedSignature = ComputeSignature(signatureBase, consumerSecret, tokenSecret); string actualSignature = Rfc3986.Decode(signature); return(expectedSignature == actualSignature); }
/// <summary> /// Send a Bad Request response with the OAuthRequestException details in the header /// and the response parameters in the body. /// </summary> /// <param name="context">HTTP context</param> /// <param name="exception">OAuth exception</param> /// <param name="responseParameters">Response parameters</param> public static void SendBadRequest(HttpContext context, OAuthRequestException exception, NameValueCollection responseParameters) { if (context == null) { throw new ArgumentNullException("context"); } if (exception == null) { throw new ArgumentNullException("exception"); } // There is a problem with the parameters; return 400 Bad Request context.Response.StatusCode = (int)HttpStatusCode.BadRequest; // Add the problem report in the WWW-Authenticate header context.Response.AddHeader( Constants.WwwAuthenticateHeaderParameter, exception.ToHeaderFormat(ServiceProviderContext.Settings.AuthenticationRealm)); // Write the response if (responseParameters != null && responseParameters.Count > 0) { context.Response.Write(Rfc3986.EncodeAndJoin(responseParameters)); } context.Response.End(); }
public void Sign(Uri requestUri, string httpMethod, IConsumer consumer, IToken token, ISignProvider signingProvider) { if (token != null) { Token = token.Token; } OAuthParameters signingParameters = Clone(); var signingUri = new UriBuilder(requestUri); // Normalize the request uri for signing if (!string.IsNullOrEmpty(requestUri.Query)) { // TODO: Will the parameters necessarily be Rfc3698 encoded here? If not, then Rfc3968.SplitAndDecode will throw FormatException signingParameters.AdditionalParameters.Add(Rfc3986.SplitAndDecode(requestUri.Query.Substring(1))); signingUri.Query = null; } if (signingProvider == null) { // There is no signing provider for this signature method throw new OAuthRequestException(null, OAuthProblemTypes.SignatureMethodRejected); } // Compute the signature Signature = signingProvider.ComputeSignature( Security.Signature.Create(httpMethod, signingUri.Uri, signingParameters), consumer.Secret, (token != null && token.Secret != null) ? token.Secret : null); }
private String getSignature() { if (signature == null) { signature = Rfc3986.Encode(getConsumerSecret()) + '&' + Rfc3986.Encode(getTokenSecret()); } return(signature); }
public ComparableParameter(OAuth.Parameter value) { this.value = value; String n = ToString(value.Key); String v = ToString(value.Value); key = Rfc3986.Encode(n) + ' ' + Rfc3986.Encode(v); // ' ' is used because it comes before any character // that can appear in a percentEncoded string. }
public string ComputeSignature(string signatureBase, string consumerSecret, string tokenSecret) { using (HMACSHA1 crypto = new HMACSHA1()) { string key = Rfc3986.Encode(consumerSecret) + "&" + Rfc3986.Encode(tokenSecret); crypto.Key = Encoding.ASCII.GetBytes(key); string hash = Convert.ToBase64String(crypto.ComputeHash(Encoding.ASCII.GetBytes(signatureBase))); crypto.Clear(); return(hash); } }
public virtual bool CheckSignature(string signatureBase, string signature, string consumerSecret, string tokenSecret) { string expectedSignature = this.ComputeSignature( signatureBase, consumerSecret, tokenSecret); string actualSignature = Rfc3986.Decode(signature); return(expectedSignature == actualSignature); }
public static string Serialize(OAuthToken token) { if (token == null) { throw new ArgumentNullException("token"); } return("[" + Rfc3986.Encode(Enum.Format(typeof(TokenType), token.Type, "G")) + "|" + Rfc3986.Encode(token.Token) + "|" + Rfc3986.Encode(token.Secret) + "|" + Rfc3986.Encode(token.ConsumerKey) + "]"); }
public void Test_AuthCore1_0_Section9_4_1_EmptyToken() { string sigBase = string.Empty; string consumerSecret = "djr9rjt0jd78jf88"; string tokenSecret = string.Empty; PlaintextSigningProvider signingProvider = new PlaintextSigningProvider(false); Assert.That(signingProvider.SignatureMethod, Is.EqualTo("PLAINTEXT")); string hash = Rfc3986.Encode(signingProvider.ComputeSignature(sigBase, consumerSecret, tokenSecret)); Assert.That(hash, Is.EqualTo("djr9rjt0jd78jf88%26")); }
public string ToNormalizedString(params string[] excludedParameters) { List <KeyValuePair <string, string> > @params = new List <KeyValuePair <string, string> >(); // Add OAuth parameters whose values are not null except excluded parameters foreach (string param in parameters.Keys) { if (parameters[param] != null && Array.IndexOf(excludedParameters, param) < 0) { @params.Add(new KeyValuePair <string, string>(Rfc3986.Encode(param), Rfc3986.Encode(parameters[param]))); } } // Add all additional parameters foreach (var param in additionalParameters.AllKeys) { foreach (var value in additionalParameters.GetValues(param) ?? new string[] { }) { @params.Add(new KeyValuePair <string, string>(Rfc3986.Encode(param), Rfc3986.Encode(value))); } } // Sort parameters into lexicographic order (by key and value) @params.Sort(CompareKeys); // Concatenate and encode string equals = "="; string ampersand = "&"; StringBuilder parms = new StringBuilder(); bool first = true; foreach (var pair in @params) { if (first) { first = false; } else { parms.Append(ampersand); } parms.Append(pair.Key).Append(equals).Append(pair.Value); } return(parms.ToString()); }
private static NameValueCollection ParseAuthHeader(string authHeader) { if (!String.IsNullOrEmpty(authHeader)) { NameValueCollection @params = new NameValueCollection(); // Check for OAuth auth-scheme Match authSchemeMatch = OAuthCredentialsRegex.Match(authHeader); if (authSchemeMatch.Success) { // We have OAuth credentials in the Authorization header; parse the parts // Sad-to-say, but this code is much simpler than the regex for it! string[] authParameterValuePairs = authHeader.Substring(authSchemeMatch.Length).Split(','); foreach (string authParameterValuePair in authParameterValuePairs) { string[] parts = authParameterValuePair.Trim().Split('='); if (parts.Length == 2) { string parameter = parts[0]; string value = parts[1]; if (value.StartsWith("\"", StringComparison.Ordinal) && value.EndsWith("\"", StringComparison.Ordinal)) { value = value.Substring(1, value.Length - 2); try { value = StringEscapeSequence.Replace(value, EvaluateAuthHeaderMatch); } catch (FormatException) { continue; } // Add the parameter and value @params.Add(Rfc3986.Decode(parameter), Rfc3986.Decode(value)); } } } } return(@params); } return(null); }
private static void EncodeHeaderValue(StringBuilder buffer, string key, string value, string separator, bool quote) { buffer.Append(separator); buffer.Append(Rfc3986.Encode(key)); buffer.Append("="); if (quote) { buffer.Append('"'); } buffer.Append(Rfc3986.Encode(value)); if (quote) { buffer.Append('"'); } }
/// <summary> /// Send a OK response with the response parameters in the body. /// </summary> /// <param name="context">HTTP context</param> /// <param name="responseParameters">Response parameters</param> public static void SendOk(HttpContext context, NameValueCollection responseParameters) { if (context == null) { throw new ArgumentNullException("context"); } // There is a problem with the parameters; return 401 Bad Request context.Response.StatusCode = (int)HttpStatusCode.OK; // Write the response if (responseParameters != null && responseParameters.Count > 0) { context.Response.Write(Rfc3986.EncodeAndJoin(responseParameters)); } context.Response.End(); }
public string ComputeSignature(string signatureBase, string consumerSecret, string tokenSecret) { StringBuilder signature = new StringBuilder(); if (!String.IsNullOrEmpty(consumerSecret)) { signature.Append(Rfc3986.Encode(consumerSecret)); } signature.Append("&"); if (!String.IsNullOrEmpty(tokenSecret)) { signature.Append(Rfc3986.Encode(tokenSecret)); } return(signature.ToString()); }
public ParametersAbsentException(string message, string[] parameters) : base(message, OAuthProblemTypes.ParameterAbsent) { this.parameters = parameters; StringBuilder sb = new StringBuilder(); for (int i = 0; i < parameters.Length; i++) { sb.Append(Rfc3986.Encode(parameters[i])); if (i < parameters.Length - 1) { sb.Append("&"); } } AddParameter(OAuthErrorParameterKeys.ParametersAbsent, sb.ToString()); }
public static string Create(string httpMethod, Uri requestUrl, OAuthParameters parameters) { StringBuilder sigbase = new StringBuilder(); // Http header sigbase.Append(Rfc3986.Encode(httpMethod)).Append("&"); // Normalized request URL sigbase.Append(Rfc3986.Encode(requestUrl.Scheme)); sigbase.Append(Rfc3986.Encode("://")); sigbase.Append(Rfc3986.Encode(requestUrl.Authority.ToLowerInvariant())); sigbase.Append(Rfc3986.Encode(requestUrl.AbsolutePath)); sigbase.Append("&"); // Normalized parameters sigbase.Append( Rfc3986.Encode(parameters.ToNormalizedString(OAuthParameterKeys.Realm, OAuthParameterKeys.Signature, OAuthParameterKeys.TokenSecret))); return(sigbase.ToString()); }
/** * 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()); }
private byte[] computeSignature(String baseString) { byte[] _key; lock (this) { if (key == null) { String keyString = Rfc3986.Encode(getConsumerSecret()) + "&" + Rfc3986.Encode(getTokenSecret()); key = Encoding.GetEncoding(ENCODING).GetBytes(keyString); } _key = key; } using (HMACSHA1 crypto = new HMACSHA1()) { crypto.Key = _key; byte[] hash = crypto.ComputeHash(Encoding.GetEncoding(ENCODING).GetBytes(baseString)); crypto.Clear(); return(hash); } }
private static String getAuthorizationHeader(IEnumerable <OAuth.Parameter> oauthParams) { StringBuilder result = new StringBuilder("OAuth "); bool first = true; foreach (var parameter in oauthParams) { if (!first) { result.Append(", "); } else { first = false; } result.Append(Rfc3986.Encode(parameter.Key)) .Append("=\"") .Append(Rfc3986.Encode(parameter.Value)) .Append('"'); } return(result.ToString()); }
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))); }
//TODO: No anda todavia!! private HttpWebResponse GetContacts() { yahooAccessToken = (string[])HttpContext.Current.Session["Yahoo_AccessToken"]; Uri RequestContactBaseUri = new Uri("http://social.yahooapis.com/v1/user/" + YGuid + "/contacts"); int timestamp = Common.GetTimestamp(); OAuthParameters parameters = new OAuthParameters(); parameters.ConsumerKey = apiKey; parameters.Nonce = new GuidNonceProvider().GenerateNonce(timestamp); parameters.SignatureMethod = "HMAC-SHA1"; parameters.Timestamp = timestamp.ToString(CultureInfo.InvariantCulture); parameters.Token = Rfc3986.Decode(AccessToken); parameters.Version = "1.0"; parameters.AdditionalParameters.Add("format", "xml"); string sigBase = SignatureBase.Create("GET", RequestContactBaseUri, parameters); HmacSha1SigningProvider singProvier = new HmacSha1SigningProvider(); parameters.Signature = singProvier.ComputeSignature( sigBase, (secret), Rfc3986.Encode(AccessTokenSecret)); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://social.yahooapis.com/v1/user/" + YGuid + "/contacts?view=tinyusercard"); request.CookieContainer = new CookieContainer(); request.Headers["WWW-Authenticate"] = " OAuth realm='yahooapis.com',"; request.Headers["WWW-Authenticate"] += " oauth_consumer_key='" + parameters.ConsumerKey + "',"; request.Headers["WWW-Authenticate"] += " oauth_nonce='" + parameters.Nonce + "',"; request.Headers["WWW-Authenticate"] += " oauth_signature_method='" + parameters.SignatureMethod + "',"; request.Headers["WWW-Authenticate"] += " oauth_timestamp='" + parameters.Timestamp + "',"; request.Headers["WWW-Authenticate"] += " oauth_token='" + token + "',"; request.Headers["WWW-Authenticate"] += " oauth_version='" + parameters.Version + "',"; request.Headers["WWW-Authenticate"] += " oauth_signature='" + parameters.Signature + "'"; request.Method = "GET"; request.ContentType = "application/xml; charset=utf-8"; return((HttpWebResponse)request.GetResponse()); }
public void TestPercent() { Assert.That(Rfc3986.Encode("%"), Is.EqualTo("%25")); }
public void TestUnicodeU007F() { Assert.That(Rfc3986.Encode("\u007F"), Is.EqualTo("%7F")); }
public void TestAmpersandEqualsAsterisk() { Assert.That(Rfc3986.Encode("&=*"), Is.EqualTo("%26%3D%2A")); }
public void TestUnicodeU0080() { Assert.That(Rfc3986.Encode("\u0080"), Is.EqualTo("%C2%80")); }
public void TestUnicodeU3001() { Assert.That(Rfc3986.Encode("\u3001"), Is.EqualTo("%E3%80%81")); }
public void TestDashDotUnderscoreTilde() { Assert.That(Rfc3986.Encode("-._~"), Is.EqualTo("-._~")); }
public static OAuthToken Deserialize(string serializedForm) { if (string.IsNullOrEmpty(serializedForm)) { throw new ArgumentException("serializedForm argument must not be null or empty", "serializedForm"); } if (!serializedForm.StartsWith("[", StringComparison.Ordinal)) { throw new FormatException("Serialized SimpleToken must start with ["); } if (!serializedForm.EndsWith("]", StringComparison.Ordinal)) { throw new FormatException("Serialized SimpleToken must end with ]"); } string[] parts = serializedForm.Substring(1, serializedForm.Length - 2) .Split(new char[] { '|' }, StringSplitOptions.None); if (parts.Length != 4) { throw new FormatException("Serialized SimpleToken must consist of 4 pipe-separated fields"); } if (string.IsNullOrEmpty(parts[0])) { throw new FormatException("Error deserializing SimpleToken.Type (field 0): cannot be null or empty"); } TokenType type; try { type = (TokenType)Enum.Parse(typeof(TokenType), Rfc3986.Decode(parts[0]), true); } catch (Exception e) { throw new FormatException("Error deserializing SimpleToken.Type (field 0)", e); } if (string.IsNullOrEmpty(parts[1])) { throw new FormatException("Error deserializing SimpleToken.Token (field 1): cannot be null or empty"); } string token; try { token = Rfc3986.Decode(parts[1]); } catch (Exception e) { throw new FormatException("Error deserializing SimpleToken.Token (field 1)", e); } string secret; try { secret = Rfc3986.Decode(parts[2]); } catch (Exception e) { throw new FormatException("Error deserializing SimpleToken.Secret (field 2)", e); } string consumerKey; try { consumerKey = Rfc3986.Decode(parts[3]); } catch (Exception e) { throw new FormatException("Error deserializing SimpleToken.ConsumerKey (field 3)", e); } return(new OAuthToken(type, token, secret, consumerKey)); }
public void TestPlus() { Assert.That(Rfc3986.Encode("+"), Is.EqualTo("%2B")); }