在WCF REST服务中实现Oauth(Siganture不匹配)

本文关键字:Siganture 不匹配 Oauth 实现 WCF REST 服务 | 更新日期: 2023-09-27 18:27:52

我在我的WCF RESTful服务中实现Oauth,在客户端,我使用脚本(脚本引用)生成签名(签名引用链接1,链接2),在服务器端,我使用c#(代码引用)生成签字,一切都很好,但唯一的问题是客户端生成签名与服务器端生成签名不匹配。

这是我的代码,请指出我在哪里犯了错误

脚本:

$("#BtnCheck").click(function () {
    oauth = OAuth({
        consumer: {
            public: 'test',
            secret: 'secret'
        },
        signature_method: 'HMAC-SHA1'
    });
   request_data = {
     //  url: 'http://MyPcName/RestfulService/Login/LoginService.svc/GetSampleMethod_With_OAuth/inputStr/validate',
       url: 'http://localhost/RestfulService/Login/LoginService.svc/GetSampleMethod_With_OAuth/inputStr/validate',
        method: 'GET',
        data: {
            status: 'Hello Ladies + Gentlemen, a signed OAuth request!'
        }
    };
   varType = "GET";
   varUrl = "http://localhost/RestfulService/Login/LoginService.svc/GetSampleMethod_With_OAuth/inputStr/validate";
   data = oauth.authorize(request_data, null);
   varContentType = "application/json; charset=utf-8";
   varDataType = "json";
   varProcessData = false;
   varCache = false
   varData = data;
   CallService(Authenticate);
});
function Authenticate(response) {
    var data = response
    alert(response);
}

呼叫服务:

function CallService(sucessData) {
    $.ajax({
        //headers: getHeaders(),
        type: varType, //GET or POST or PUT or DELETE verb
        url: varUrl, // Location of the service
        data: varData, //Data sent to server
        contentType: varContentType, // content type sent to server
        dataType: varDataType, //Expected data format from server
        processdata: varProcessData, //True or False
        crossDomain: true,
        timeout: 200000,
        success: sucessData,
        cache: varCache,
        error: function (xhr) {// When Service call fails
            alert("Error: " + xhr.responseText);
            //alert('Error occured in Service Call');
        }
    });
}

WCF服务:

        [OperationContract(Name = "GetSampleMethod_With_OAuth")]
        [WebGet(UriTemplate = "GetSampleMethod_With_OAuth/inputStr/{name}")]
        string GetSampleMethod_With_OAuth(string name);
 public string GetSampleMethod_With_OAuth(string strUserName)
        {
            if (Authenticate(WebOperationContext.Current.IncomingRequest))
            {
                StringBuilder strReturnValue = new StringBuilder();
                // return username prefixed as shown below
                strReturnValue.Append(string.Format("AUTHORIZED REQUEST"));
                return strReturnValue.ToString();
            }
            else
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized;
                return "401 Unauthorized Request.";
            }
      }
        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 = "secret";
                OAuthBase oauth = new OAuthBase();
                string hash = oauth.GenerateSignature(
                    new Uri(uri),
                    pa["oauth_consumer_key"],
                    consumersecret,
                    null, // totken
                    null, //token secret
                    "GET",
                    pa["oauth_timestamp"],
                    pa["oauth_nonce"],
                    out normalizedUrl,
                    out normalizedRequestParameters
                    );
                Authenticated = pa["oauth_signature"] == hash;
            }
            return Authenticated;
        }

在WCF REST服务中实现Oauth(Siganture不匹配)

我找到了这个问题的解决方案:

在Javascript中:删除request_data 中的data:{}

 request_data = {
     //  url: 'http://MyPcName/RestfulService/Login/LoginService.svc/GetSampleMethod_With_OAuth/inputStr/validate',
       url: 'http://localhost/RestfulService/Login/LoginService.svc/GetSampleMethod_With_OAuth/inputStr/validate',
        method: 'GET',
            };