[英]WCF service and oauth + jQuery ajax call
I was trying to implement oauth authentication in my WCF service. 我试图在WCF服务中实现oauth身份验证。 I am doing the service call from jQuery ajax.
我正在从jQuery ajax进行服务调用。 I have tried the following code in CORS enabled service with POST verb.
我在带有POST动词的启用CORS的服务中尝试了以下代码。 But here I am getting pa["oauth_consumer_key"] as always null.
但是在这里,我得到的pa [“ oauth_consumer_key”]始终为null。 Please see the code and help me to find out the issue.
请查看代码,并帮助我找出问题所在。
Using POST and CORS 使用POST和CORS
jQuery ajax call:- jQuery ajax调用:-
function logClick() {
var sEmail = $('#username').val();
var sPassword = $('#password').val();
var key = "test";
var oauth_signature = "xxxxxxx";
var timestamp = (new Date()).getTime();
var nonce = Math.random();
var auth_header = 'OAuth oauth_nonce="' + nonce + '"' +
', oauth_signature_method="HMAC-SHA1"' +
', oauth_timestamp="' + timestamp + '"' +
', oauth_consumer_key="' + key + '"' +
', oauth_signature="' + oauth_signature + '"' +
', oauth_version="1.0"';
var userData = '{"email":"' + sEmail + '","password":"' + sPassword + '"}';
$.support.cors = true;
$.ajax({
data: userData,
type: "POST",
dataType: "json",
contentType: "application/json;charset=utf-8",
url: "http://mydomain/MyAppService.svc/UserValidation",
beforeSend : function(xhr, settings) {
$.extend(settings, { headers : { "Authorization": auth_header } });
},
success: function (msg) {
alert("success");
},
error: function () {
alert("Network error");
}
});
}
WCF service code WCF服务代码
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "UserValidation")]
int UserValidation(string email,string password);
public int UserValidation(string email, string password)
{
if (Authenticate(WebOperationContext.Current.IncomingRequest))
{
//my code
return 1;
}
else
{
return 0;
}
}
private static bool Authenticate(IncomingWebRequestContext context)
{
bool Authenticated = false;
string normalizedUrl;
string normalizedRequestParameters;
NameValueCollection pa = context.Headers;
//NameValueCollection pa = context.UriTemplateMatch.QueryParameters;// tried this also
if (pa != null && pa["oauth_consumer_key"] != null) // pa["oauth_consumer_key"] is always null
{
// to get uri without oauth parameters
string uri = context.UriTemplateMatch.RequestUri.OriginalString.Replace
(context.UriTemplateMatch.RequestUri.Query, "");
string consumersecret = "suryabhai";
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;
}
I did the same aouth authentication in GET and JSONP . 我在GET和JSONP中进行了相同的身份验证。 Following is the code.
以下是代码。 Here the authentication is working, but I am not getting the result even though the service return data.
此处的身份验证有效,但是即使服务返回数据也无法获得结果。 ( entering to error block in jQuery ajax call)
(进入jQuery ajax调用中的错误块)
GET and JSONP GET和JSONP
jQuery ajax call:- jQuery ajax调用:-
function getData() {
$.ajax({
url: "http://mydomain/MyAppService.svc/GetData/328?oauth_consumer_key=test&oauth_nonce=10a33ed37b549301644b23b93fc1f1c5&oauth_signature=AMTsweMaWeN7kGnSwoAW44WKUuM=&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1289976718&oauth_version=1.0?callback=?",
type: "GET",
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
processdata: true,
success: function (msg) {
alert("success");
},
error: function error(response) {
alert(" Network Error"); // always entering to this block
}
});
WCF service :- WCF服务:-
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "GetData/{ParentID}")]
List<Parent> GetData(string ParentID);
public List<Parent> GetData(string ParentID)
{
List<Parent> ParentList = new List<Parent>();
if (Authenticate(WebOperationContext.Current.IncomingRequest)) // it is working
{
//my code
return ParentList ; // result is getting, but on client it is going to error block of jQUery ajax call
}
else
{
return ParentList ;
}
}
private static bool Authenticate(IncomingWebRequestContext context)
{
bool Authenticated = false;
string normalizedUrl;
string normalizedRequestParameters;
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 = "suryabhai";
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;
}
Web.config:- Web.config:-
<?xml version="1.0"?>
<configuration>
<system.web>
<authentication mode="None" />
<httpRuntime maxRequestLength="2147483647"/>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true"/>
<services>
<service name="DataAppAppService.MyAppService">
<endpoint address="" behaviorConfiguration="webHttpBehavior" binding="webHttpBinding" bindingConfiguration="WebHttpBindingWithJsonP" contract=DataAppAppService.IMyAppService" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="WebHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647" transferMode="Streamed"
>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceThrottling maxConcurrentCalls="30" maxConcurrentInstances="30" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<directoryBrowse enabled="true" />
</system.webServer>
</configuration>
I was able to solve the "Using POST and CORS" issue. 我能够解决“使用POST和CORS”问题。 I have added the Authorization header into "Access-Control-Allow-Headers" and it solved the issue.
我已经将授权标头添加到“ Access-Control-Allow-Headers”中,它解决了该问题。
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");
Is there any way to generate oauth_signature from javascript. 有没有办法从javascript生成oauth_signature。 Now I am hard coding the value, but as the timestamp and oauth_nonce changing each time, I am getting different signature.
现在,我正在对值进行硬编码,但是随着时间戳和oauth_nonce每次更改,我得到了不同的签名。 SO I need to pass the correct signature through the ajax request rather than giving hard coding value.
所以我需要通过ajax请求传递正确的签名,而不是提供硬编码值。 Please give a suggestion.
请给个建议。
But still I have issue with Get and JSONP and oAuth. 但是,Get,JSONP和oAuth仍然存在问题。 Any thoughts?
有什么想法吗?
Thanks. 谢谢。
"But still I have issue with Get and JSONP and oAuth. Any thoughts?" “但是我仍然对Get和JSONP和oAuth存有疑问。有什么想法吗?” --> I could solve this issue using GET method with CORS.
->我可以使用带有CORS的GET方法解决此问题。 Here is my code.
这是我的代码。
$.support.cors = true;
$.ajax({
type: "GET",
dataType: "json",
contentType: "application/json;charset=utf-8",
url: "http://mydomain:89/MyAppAppService.svc/GetFolders",
beforeSend: function (xhr) {
var username = "test";
var password = "testpwd";
xhr.setRequestHeader("Authorization", "Basic " + $.base64('encode', username + ':' + password));
},
success: function (msg) {
alert("Success");
},
error: function (jqXHR, status, message) {
alert(jqXHR.responseText);
alert(status + " " + message);
}
});
Thanks. 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.