我有以下代码调用OAuth类的GenerateSignature方法
Uri u = new Uri(urlToCall);
string url, param;
HttpWebRequest request = WebRequest.Create("http://localhost/RESTFUL_DEMO.Web/services/Calc.svc/dowork") as HttpWebRequest;
string consumerKey = "test";
string consumerSecret = "Jenish";
var oAuth = new OAuthBase();
var nonce = oAuth.GenerateNonce();
var timestamp = oAuth.GenerateTimeStamp();
var signature = oAuth.GenerateSignature(u,consumerKey,consumerSecret,string.Empty,string.Empty,"POST",timestamp,nonce,OAuthBase.SignatureTypes.HMACSHA1,out url, out param);
WebRequest request = WebRequest.Create(string.Format("{0}?{1}&oauth_signature={2}", urlToCall, param, signature));
request.Method = "POST";
Enroll a = new Enroll("2");
XmlSerializer ser = new XmlSerializer(a.GetType());
MemoryStream ms = new MemoryStream();
ser.Serialize(ms, a);
byte[] bytes = ms.ToArray();
request.ContentType = "text/xml";
request.Timeout = 30000;
request.ContentLength = bytes.Length;
var requeststream = request.GetRequestStream();
requeststream.Write(bytes, 0, bytes.Length);
requeststream.Close();
WebResponse response = request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
我在我的服务中创建了以下Authenticate方法,该方法从传入请求生成签名
private static bool Authenticate(IncomingWebRequestContext context)
{
bool Authenticated = false;
string normalizedUrl;
string normalizedRequestParameters;
//context.Headers
NameValueCollection pa = context.UriTemplateMatch.QueryParameters;
if (pa != null && pa["oauth_consumer_key"] != null)
{
// to get uri without oauth parameters
string uri = context.UriTemplateMatch.RequestUri.OriginalString.Replace
(context.UriTemplateMatch.RequestUri.Query, "");
string consumersecret = "Jenish";
OAuthBase oauth = new OAuthBase();
string hash = oauth.GenerateSignature(
new Uri(uri),
pa["oauth_consumer_key"],
consumersecret,
null, // totken
null, //token secret
"POST",
pa["oauth_timestamp"],
pa["oauth_nonce"],
out normalizedUrl,
out normalizedRequestParameters
);
Authenticated = pa["oauth_signature"] == hash;
}
return Authenticated;
}
Above Authenticate方法生成的签名与传入请求参数pa [“oauth_signature”]不匹配。任何人都可以帮我解决问题,让我知道为什么会生成两个不同的签名。
答案 0 :(得分:1)
我尝试通过考虑上面的代码来复制您的错误,并发现从
生成的uricontext.UriTemplateMatch.RequestUri.OriginalString
Authenticate方法中的确实生成了Uri的完全限定机器名而不是localhost。所以在你的wcf消费者方面,HttpWebRequest请求uri应该包括完全限定的机器名和域名。
例如 如果您的机器名称为Jenish-pc,域名为abc.efg.com,那么uri应该像
http://Jenish-pc.abc.efg.com/[rest of your service path]
而不是
http://localhost/....