How to correctly login user in mobile app built with PhoneGap - asp.net

Im building a mobile app on a PhoneGap. I've created several static HTML pages (stored on the phone locally) and trying to load some data from server using AJAX.
$( document ).bind( "mobileinit", function() {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
});
$(document).ready(function () {
ajaxDeferred = $.ajax({
url: 'http://example.com/api/isAuthorized'
type: method,
data: parameters,
timeout: 40000
});
ajaxDeferred
.done(function(data) {
alert(data.result);
})
.fail(onFailHandler);
});
On a server side I have this code
public ActionResult IsAuthorized()
{
FormsAuthentication.SetAuthCookie("shade", true);
return this.Json(
new
{
result = this.HttpContext.User.Identity.IsAuthenticated
},
JsonRequestBehavior.AllowGet
);
}
I expect:
On the first run recieve "False" result since user is not authorized
On the second run recieve "True", because of SetAuthCookie
When I try it in a browser, it works as expected.
But whatever I run mobile app i alwayes recieve False, like cookies are not being tranfered.
So the question is how to correctly login user with AJAX, is it possible?
What are best practises? For unknown reason this simple scenario is not covered by PhoneGap manuals.

Ok, I found an answer:
$(document).ready(function () {
...
});
is not suitable. Instead one have to use
document.addEventListener(
"deviceready",
function() {
... at this point cookies are working fine!
},
false);
Access-Control-Allow-Origin and Access-Control-Allow-Credentials headers are not required as well as other cross-domain techniques

Related

Scraping an ASP.NET website with NodeJS

i am trying to login to my supplier website programatically and get the resseller price by code. i have my username and password provided by the supplier to use in the website which is powred by ASP.NET. i tried to use the request module but got no luck with it.
this the code i used so far :
var request = require('request');
var j = request.jar();
var request = request.defaults({ jar : j }) //it will make the session default for every request
//...
request({
url:"https://www.XXXXX.com/login.aspx",
method:"POST",
form:{
ctl00$cpholder$txtUserName:"YYYYYYYY",
ctl00$cpholder$txtPassword:"ZZZZZZZZ"
}
},
function(err,response,body){
console.log(err);
// here i try to access the product page like a reseller
request({
url:"https://www.XXXXXX.com/productdetails.aspx?id=20000028&itemno=90NB0CL1-M08420",
method:"GET",
}, function(err, response, body){
console.log(err);
//Some logic
});
});
}
this is the login form code ( in pastebin because it is very long )
https://pastebin.com/kwuRdLX4
please help

How to get Google+ profile with Meteor.loginWithGoogle?

I'm looking for a working example of Meteor.loginWithGoogle (with meteor 0.6.4.1).
I found this one for loginWithGitHub (https://www.eventedmind.com/posts/meteor-customizing-login) that works fine with GitHub.
It works fine without parameters as show here on client side :
Template.user_loggedout.events({
"click #login": function(e, tmpl){
Meteor.loginWithGoogle({
}, function (err) {
if(err) {
//error handling
alert('error : '+err.message);
} else {
}
});
}
});
with the Accounts params on server side :
Accounts.loginServiceConfiguration.remove({
service: 'google'
});
Accounts.loginServiceConfiguration.insert({
service: 'google',
clientId: 'XXXXXX',
secret: 'YYYYYY'
});
In this case how can i get currentUser information especially the mail ?
Is there a way to get the Google+ profile of the user (if he has one and allows this), the user's avatar for example ?
What are the needed parameters for requestPermissions: , what can i get with this ?
Thanks
After some research i build my own example available here : https://github.com/lc3t35/googlelogin
Thanks to :
https://github.com/m2web/githublogin
https://github.com/ananta-IO/marq
Meteor/MongoDB see available fields for publish?
https://github.com/mrtnbroder/meteor-snippets/blob/master/snippets/js/Accounts/loginWithGoogle.sublime-snippet
https://developers.google.com/accounts/docs/OAuth2Login#obtaininguserprofileinformation

HandleUnauthorizedRequest in ASP.Net Web API

I am developing a ASP.Net Web API application and I have used AuthorizeAttribute for the authentication. When the authentication fails, the code that executes is this.
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
return;
}
This code results to display a Unauthorized request page from the browser but what I want is to display a custom page which I have designed. How do I do that?
Check this out: http://weblogs.asp.net/jgalloway/archive/2012/03/23/asp-net-web-api-screencast-series-part-6-authorization.aspx
What it basically says, you have to check the result code on the client side, and in case it is 401 (Unauthorized), redirect the user to the custom page you've designed:
$(function () {
$("#getCommentsFormsAuth").click(function () {
viewModel.comments([]);
$.ajax({ url: "/api/comments",
accepts: "application/json",
cache: false,
statusCode: {
200: function(data) {
viewModel.comments(data);
},
401: function(jqXHR, textStatus, errorThrown) {
self.location = '/Account/Login/';
}
}
});
});
});
I don't think you can redirect to your custom page from within HandleUnathorizedRequest if you are using WebApi. The code result displays Unauthorized request page because that is how your browser responds to 403 code. WebApi works on HttpMessage exchange and by default uses either Json or Xml media type. If you want to return your customized page as text/html then you will have to write your own media formatter as explained here: http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters.

Jquery Ajax, not working in Internet explorer

I'm trying to do some jQuery ajax and it works in Firfox and Chrome, but not in internet explorer 9.
The final code will have to go across sub-domains, and this doesn't work in ie with the default transport.
So I'm trying to create a custom transport to use in internet explorer
Method 1
$.ajaxTransport("+*", function (options, originalOptions, jqXHR) {
if (jQuery.browser.msie && window.XDomainRequest) {
var xdr;
return {
send: function (headers, completeCallback) {
// Use Microsoft XDR
xdr = new XDomainRequest();
xdr.open("get", options.url);
xdr.onload = function () {
if (this.contentType.match(/\/xml/)) {
var dom = new ActiveXObject("Microsoft.XMLDOM");
dom.async = false;
dom.loadXML(this.responseText);
completeCallback(200, "success", [dom]);
} else {
completeCallback(200, "success", [this.responseText]);
}
};
xdr.ontimeout = function () {
completeCallback(408, "error", ["The request timed out."]);
};
xdr.onerror = function () {
completeCallback(404, "error", ["The requested resource could not be found."]);
};
xdr.send();
},
abort: function () {
if (xdr) xdr.abort();
}
};
}
});
I've created a simple sample page to demonstrate the first technique here:
http://services.whygo.net/sendAjax.htm
Please note if you use the custom transport the normal transport will then fail unless you refresh
The idea comes from here:
http://forum.jquery.com/topic/cross-domain-ajax-and-ie#14737000002203097
This give no error message other than 'error' inside the 'error' method called on $ajax, when it fails. I do get a 405 Method not allowed on the 'Network' tab of if dev tools, but the server side stuff does execute.
Method 2
I have also tried another method as described here:
Cross-subdomain AJAX works in Chrome, not IE
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
// override default jQuery transport
jQuery.ajaxSettings.xhr = function() {
try { return new XDomainRequest(); }
catch(e) { }
};
}
This can be found here:
http://www.whygo.net/sendAjax2.html
On this one I actually get 200 codes on the 'network' tab of ie dev tools, but doesn't call the 'error' or the 'success' pararm of $ajax.
If I put a timeout on this second one, then it returns to the 'error' function with a message of 'timeout'.
Here's the solution I went with after about a day of struggling with this inconsistency...
// new method as to not overwrite jQuery's defaults
var cors = (window.XDomainRequest) ? function(url, callback) {
var xdr = new XDomainRequest();
xdr.open('get', url);
xdr.onload = function() { callback(xdr.responseText); }
xdr.send();
} : $.get; // else, use jQuery's method
Use...
cors(url, function(msg) { alert(msg); }); // pretty well same as $.get
Copy and paste, this of course doesn't serve all purposes, but it's a start and it works.
On the http://services.whygo.net/sendAjax2.html page, I see that you've got the expected dataType of the AJAX response coming back from the server as JSON, but the response actually comes back as a plain text string ("Email successfully sent.").
Perhaps you could try commenting out dataType and let jQuery figure out what type of response comes back.

Calling a function / database update using Ajax via Jquery

Im creating a simple "Was this useful?" form with Yes and No objects- Using ASP.net webforms.
I need the submission to be done via ajax using jquery, to prevent a user from voting multiple times on the same page.. currently i have two methods Like_Click and Dislike_click in the C# code behind the page in question.
Can anyone give me some pointers on or a link to any suitable walkthroughs for simple ajax via jquery (I'm new to ajax!)
Ive looked at using the [WebMethod] identifier on each of the methods but do not really understand this method fully.
thanks
You are probably looking for jQuery's post function. Check out the examples. You'll want to do something along the lines of:
$('.myForm').submit(function(){ //define a handler for the submit event of the form
$.post($(this).attr('action'), {useful: true}); //send data via ajax
return false; //prevents the form from submitting via a normal web request
});
You can try something like below
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
var like = $('#Like').val();
var dislike = $('#Dislike').val();
if (name != '' && email != '') {
$.ajax
({
type: 'POST',
url: 'Home.aspx/UpdateDB', //UpdateDB is declared as WebMethod
async: false,
data: "{'like':'" + like + "','dislike':'" + dislike + "'}",
contentType: 'application/json; charset =utf-8',
success: function (data) {
var obj = data.d;
if (obj == 'true') {
$('#Like').val('');
$('#Dislike').val('');
alert("Data Saved Successfully");
}
},
error: function (result) {
alert("Error Occured, Try Again");
}
});
}
})
});
</script>
Webmethod is shown below
[WebMethod]
public static string UpdateDB(string like, string dislike)
{
//Add your stuff
}
take a look more details here Call WebMethod from jquery in ASP.NET

Resources