Sending data to Restful WCF service using ExtJS - wcf

This is how my WCF service is defined to authenticate a user:
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
string validateUser(string username, string password);
It simply returns "Validated" or "NotValidated" as result.
And my ExtJS code is:
function loginclick(btn) {
var form = mainPanel.getForm();
if (form.isValid()) {
var userget = Ext.getCmp('txtuser').value;
var passget = Ext.getCmp('txtpass').value;
var myparams = { 'username': userget, 'password': passget };
Ext.Ajax.request({
url: 'http://localhost:52984/ExtJsRestfulService.svc/validateUser',
params: Ext.encode(myparams),
method: 'POST',
headers: this.header || { 'Content-Type': 'application/json;charset=utf-8' },
success: function (response, options) {
var s = response.responseText;
Ext.MessageBox.alert('Success', s);
},
failure: function (response, options) {
Ext.MessageBox.alert('Failed', 'Unable to get');
}
});
}
}
When i click on the login button, I get bad request(400) error. My service is not in the same solution. When I post the data to an aspx form in the same solution it works. What am I doing wrong?

What about:
Ext.Ajax.request({
url: 'http://yourdomain:52984/ExtJsRestfulService.svc/validateUser?username='+userget+'&password='+passget,
params: Ext.encode(myparams),
method: 'GET',
headers: this.header || { 'Content-Type': 'application/json;charset=utf-8' },
success: function (response, options) {
var s = response.responseText;
Ext.MessageBox.alert('Success', s);
},
failure: function (response, options) {
Ext.MessageBox.alert('Failed', 'Unable to get');
}
});
Can you fetch the params from the url?

Have you tried without encoding?
try
params: {
'username': userget,
'password': passget
}
Why do you have two times the params config?
You shouldn't use Ext.getCmp instead use Ext.ComponentQuery.query('myXtype[itemId=myItemId]')[0]; http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.ComponentQuery
or
define the service in a manner that the call to it would be fullfilled like
string validateUser();
then inside the service do something similar to:
String pass = request.getParameter("password");
Like in java

Related

POST command missing parameters in SSL (https:) but working with http

I have an ASMX web service for login into the website.
I call the web service by using an ajax request.
this works as intended on non-SSL (HTTP). However, when running in SSL (https)
I got an error message as below.
{"Message": "Invalid web service call, missing value for parameter: 'username'.",
"StackTrace": "
at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)
at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)
at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)
at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType": "System.InvalidOperationException"
}
Here is my ASMX web service.
using System.Web.Security;
using System.Web.Services;
namespace MyWebSite
{
[WebService(Namespace = "https://mywebsite.net")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class AuthService : System.Web.Services.WebService
{
[WebMethod]
public bool Login(string username, string password)
{
if (Membership.ValidateUser(username, password)){
FormsAuthentication.SetAuthCookie(username, true);
return true;
}
else {
return false;
}
}
}
}
And this is the ajax for call the web service.
function login(event) {
if ($('#form1').validate().form()) {
$.ajax({
type: 'POST',
url: 'Services/AuthService.asmx/Login',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({
username: $('#inputUsername').val(),
password: $('#inputPassword').val()
}),
success: function (response) {
$('#btn-login').removeAttr('disabled');
//
if (response.d) {
window.location.href = 'default.aspx';
}
},
error: function (response) {
var err = $.parseJSON(response.responseText);
console.log(err.message);
}
});
}
}
Please help me. Thanks in advance!

Google OAuth2 in external window Asp.Net Core

I'm trying to implement google oauth external authorization to happen in external browser window. My code looks like below:
$('#signinButton').click(function () {
window.auth2.grantOfflineAccess()
.then(signInCallback)
.catch(error => console.log(error));
});
function start() {
gapi.load('auth2', function () {
window.auth2 = gapi.auth2.init({
client_id: 'CLIENT_Id'
});
});
};
function signInCallback(authResult) {
if (authResult['code']) {
var authCode = authResult['code'];
$.ajax({
type: 'POST',
url: '/Auth/GooglePostredirect',
data: authCode,
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function (result) {
},
processData: false,
});
} else {
}
};
And the question is after getting authToken, how i should call google api to get user info by auth token. Is there any handy libraries for that? I can't find any to request userInfo by token from c#.
Thanks you all in advance!
You can use Google.Apis.Auth library from nuget package manager, and get info from google token, which you get from your front-end
public async Task<IActionResult> ExternalLoginGoogleAsync(string googleTokenId)
{
GoogleJsonWebSignature.ValidationSettings settings = new GoogleJsonWebSignature.ValidationSettings();
settings.Audience = new List<string>() { Configuration["Authentication:Google:ClientId"] };
GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(googleTokenId, settings);
ApplicationUser user = await _userManager.FindByEmailAsync(payload.Email);
if (user == null) //create new user if not exsits
{
user = new ApplicationUser
{
Email = payload.Email,
UserName = payload.Name
};
...
}
return Ok(something);
}

How to configure WCF RESTful endpoint for client-side jQuery calls

Can some one show me how to configure the WCF Endpoint for the following RESTful Web Service to be called from a JQuery Ajax call. My example service code:
namespace MyService
{
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
[OperationContract]
[WebGet(UriTemplate = "/GetDepartment")]
public Department GetDepartment()
{
... code
};
return data;
}
}
jQuery code:
var jData = {};
$.ajax({
cache: false,
type: "POST",
async: true,
url: "MyService/GetDepartment",
data: JSON.stringify(jData),
contentType: "application/json",
dataType: "json",
success: function (jsondata) {
... code
},
error: function (xhr) {
alert(xhr.responseText);
}
});
Try following-
function SaveBook() {
var bookData = {};
$.ajax({
type: “POST”,
url: “MyService/GetDepartment″,
data: JSON.stringify(bookData),
contentType: “application/json; charset=utf-8″,
dataType: “json”,
processData: true,
success: function (data, status, jqXHR) {
alert(“success…” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}

Passing form collection with Knockout.js in asp.net MVC

I am new to MVC and I am trying to create an application with Knockout.js to send data back to the server dynamically. I am following an example i found at:
http://www.mytecbits.com/microsoft/dot-net/knockout-js-and-bootstrap-with-asp-net-mvc-part-2
It works perfectly off the site, but i am trying to send data to multiple models instead just one as in the example
The Knockout code used in the example to send the data back to the server is
var urlPath = window.location.pathname;
var CreateArticleVM = {
Title: ko.observable(),
Excerpts: ko.observable(),
Content: ko.observable(),
Test: ko.observable(),
btnCreateArticle: function() {
$.ajax({
url: urlPath + '/Create',
type: 'post',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function(result) {
window.location.href = urlPath + '/';
},
error: function(err) {
if (err.responseText == "success") {
window.location.href = urlPath + '/';
}
else {
alert(err.responseText);
}
},
complete: function() {}
});
}
};
ko.applyBindings(CreateArticleVM);
How do i modify the above code to be able to accept a FormCollection? Or what is the best solution to my problem?
Thanks
Say your service is expecting more than one argument like following.
[HttpPost]
public String Create(ModelA modela, ModelB modelb)
{
//Server code.
}
In order pass the data for Create method from client side you need to form your postdata as follows.
$.ajax({
url: urlPath + '/Create',
type: 'post',
dataType: 'json',
data: {modela: { "modela data in the expected form" }, modelb : { "modelb data.." } },
contentType: 'application/json',
success: function(result) {
window.location.href = urlPath + '/';
},
.
.
.
.
});

sencha touch2 Login examples

I need a cross-domain user login request instance, please help me, thank you!!
My code
Ext.data.JsonP.request({
url: 'http://25.30.2.3:8080/newvbo/applyaction!longin',
params: {
username:'13881901678',
password:'111111',
},
success: function(response, opts) {
alert('1');
},
failure: function(response, opts) {
alert('2');
}
});
My question is, I not receive the server returns the value, I wrong?
You can Try this
Ext.Ajax.request({
method:'GET',
contentType:'application/json; charset=utf-8',
dataType:'json',
url:'http://........Login',
disableCaching: false,
withCredentials: true,
useDefaultXhrHeader: false,
callbackKey: 'callback',
params: {
EmailId:Ext.getCmp('usernametwoway').getValue(),
Password:Ext.getCmp('loginpasswordtwoway').getValue(),
},
success:function(response)
{
console.log(response);
var res = response.responseText;
var jsonarr = Ext.decode(response.responseText);
console.log(jsonarr);
var myres = jsonarr[0].Result;
console.log(myres);
switch(myres)
{
case '1':
console.log("Registration response is successfully");
Ext.Viewport.setActiveItem({xtype:'passengerdetailstwoway'});
break;
case '0':
console.log("Failed");
Ext.Msg.alert("Error","Login Failed",Ext.emptyFn);
break;
Based on the responce you can Specify the Switch case..
Hi #jesse you can try for cross-domain something like this,
Ext.Ajax.request({
url: 'your_url_path',
timeout: 90000,
params: {
withCredentials: true,
useDefaultXhrHeader: false,
username:'13881901678',
password:'111111',
},
success: function(response, o) {
if(response != '') {
alert('1')
}
},
failure: function(response, o) {
alert('2')
}
})
For cross-domain you need put withCredentials: true and useDefaultXhrHeader: false.
I hope help you.
I would like to suggest you a different approach because sending login credentials as GET parameter to remote server over http is not a good idea, instead you should use POST method over HTTPS. Now you would think JSONP doesn't support POST so how can I do this, but if you are going to install your app on Phone or iPad it would do remote call from browser without using JsonP, which means you can use normal AJAX proxy to do whatever you want. Check this out:
How to use json proxy to access remote services during development
Which means this should work:
var obj = new Object();
obj.userId = username;
obj.password = password;
var data = Ext.JSON.encode(obj);
Ext.Ajax.request({
url : 'https://login_url',
method : "POST",
headers: {
'Content-Type': 'application/json'
},
params : data,
useDefaultXhrHeader : false,
withCredentials: true,
success : function(response) {
},
failure : function(response) {
}
});