Developer forum

Forum » Templates » DW autologin with Ajax-Json

DW autologin with Ajax-Json

Dmitrij Jazel
Reply

Hi guys,

I have a login form, that works great.

And there I am using this line:

<input name="DWExtranetUsernameRemember" type="hidden" value="True"> 
<input name="DWExtranetPasswordRemember" type="hidden" value="True">  
<input name="Autologin" type="checkbox" checked="checked" value="True">

And it works just fine.

 

Question: when I am trying to use same approach of sending data with Ajax call, in JQuery I am including Username and Password + DWExtranetUserNameRemember + DWExtranetPasswordRemember + Autologin.

Any reason why DW would not remember my login?

 

So my data looks something like this:

&username=myuser&password=test123&DWExtranetUsernameRemember=True&DWExtranetPasswordRemember=True&Autologin=True

To send data I am using ajaxGetRequest()

xmlhttp.open("GET", url, true);

/Dmitrij

 


Replies

 
Nicolai Høeg Pedersen
Reply

Autologin sets a cookie. Ajax is using a WebClient(); It does not support cookies... So you need to fix that somehow.

​See this: http://stackoverflow.com/questions/14551345/accept-cookies-in-webclient

But be aware that there is a difference in javascript cookies and .NET cookies. (HttpOnly)

 
Dmitrij Jazel
Reply

Hi Nicolai,

Thanks for respose, so I must just set a .NET cookie value right? :)

I can try setting this one in my JSon page (it's razor), if parameter autologin is requesting it.

 

But what cookie should I set in this case, and what value must I asign?

 

Let's say if I am getting autologin = true -> so I must set autologin cookie to True (can I have an example for that)?

and if I am getting utologin = false-> so I must set autologin cookie to False (can I have an example for that aswell)?

 

/Dmitrij

 

 
Dmitrij Jazel
Reply

In other words what Cookie should I set to what value? :)

 

/Dmitrij

 
Nicolai Høeg Pedersen
Reply

Hi Dmitrij

When you set a cookie it is sent to the client - that is the browser. When you do anything in Ajax, the client is no longer the browser, but the javascript WebClient. So setting a cookie in your JSon page will not help - DW does that already... But you set it to the WebClient, and that does not handle cookies.

The cookie to set:
HttpCookie cookie = HttpContext.Current.Request.Cookies("DW_Extranet");
cookie("AL") = "True";

​But you need to set the cookie using Javascript - and in a way so .NET can read it...

(Or you can do the hacky way and submit the login form to a hidden iframe - looks and behaves almost like Ajax :-))

Happy coding!

 
Dmitrij Jazel
Reply

Hi Nicolai,

Trying to use this, but am getting Null pointer exception in any way I try using this cookie, any idea what can be wrong?

HttpCookie extranetCookie = HttpContext.Current.Request.Cookies["DW_Extranet"];
extranetCookie.Values["AL"] = "True";

I remember I used to write dirrectly into cookie, but appearently in your your example above, DW_Extranet cookie, nas "AL" value, that must have value "True" in order for this to work, I guess that is right way of thought?

Things I also tried:

Write cookie back to Response (same null pointer)

HttpCookie extranetCookie = HttpContext.Current.Request.Cookies["DW_Extranet"];
extranetCookie.Values["AL"] = "True";
HttpContext.Current.Response.Cookies.Add(extranetCookie);  

Also this, but had nullpointer aswell.

HttpContext.Current.Request.Cookies["DW_Extranet"]["AL"] = "True";

/Dmitrij

 
Dmitrij Jazel
Reply

is that the way to do it, or should I try doing something else?

/Dmitrij

 
Morten Bengtson
Reply
This post has been marked as an answer

I think you just need to use POST instead of GET. Try something like this...

jQuery.ajax({
    method: "POST",
    url: window.location.pathname + window.location.search,
    data: {
        username: "test",
        password: "test",
        DWExtranetUsernameRemember: true,
        DWExtranetPasswordRemember: true,
        Autologin: true
    }
})
.done(function (data) {
    alert("ok");
});

If you are using custom urls you need to make sure that the request is not being redirected. Use Fiddler to see what happens and ensure that the request/response looks similar to when using a regular login form. 

Votes for this answer: 1
 
Dmitrij Jazel
Reply

Hi Morten,

Well I got some progress a bit, atlest some more clues.

As soon as I change it to Post, instead of Get I am getting a null pointer excption (in JSon template) not sure what is that all about.

If I change it back to Get, all is OK again.

I am not using anything extra ordinary that would give null pointer, in JSon template trying to keep it as save as possible to avoid those.

here is my implementation of the call and post:

function jsonLoggin(pageid) {
    var username = $("#inputEmail").val();
    var password = $("#inputPassword").val();
    var DWExtranetUsernameRemember = $("input[name='DWExtranetUsernameRemember']").val();
    var DWExtranetPasswordRemember = $("input[name='DWExtranetPasswordRemember']").val();
    var Autologin = $("input[name='Autologin']").val(); //this DOES work!
    
    var data = "&username=" + username;
    data += "&password=" + password;
    data += "&DWExtranetUsernameRemember=" + DWExtranetUsernameRemember;
    data += "&DWExtranetPasswordRemember=" + DWExtranetPasswordRemember;
    data += "&Autologin=" + Autologin;

    ajaxGetRequest(data, pageid, ajaxLoginCaptured);
    //ajaxPostRequest(data, pageid, ajaxLoginCaptured);
}

function ajaxLoginCaptured() {
    var xmlhttp = arguments[0].target;
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        try {            
            var response = JSON.parse(xmlhttp.responseText);            
            if (response.userstatus == "OK" && response.grantAccess == "True") {
                //reload GUI
                location.reload();            
            } else {
                alert("Something is wrong - here is response:" + xmlhttp.responseText);
            }
        } catch (e) {
            alert("Login ajax exception:" + e.toString());            
        }
    }
}

// general POST method
function ajaxPostRequest(data, pageid, callbackHandler) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = callbackHandler;
    var url = "Default.aspx?ID=" + pageid+data;
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(data);
}

// general GET method
function ajaxGetRequest(data, pageid, callbackHandler) { 
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = callbackHandler;
    var url = "Default.aspx?ID=" + pageid + data;
    //alert("step2) "+url);
    xmlhttp.open("GET", url, true);
    xmlhttp.send(data);
}


/Dmitrij

 

 
Dmitrij Jazel
Reply

But if that is the question of setting the .Net cookie, and that's all there is, it should be doable in Razor template of JSon response, right?

 
Morten Bengtson
Reply

I don't think you need to worry about the cookies. They should work just fine. DW takes care of that.

There are some issues with the way you are using XMLHttpRequest to send data and it causes an exception in the SQL injection prevention in DW.

I never use XMLHttpRequest directly because it is easy to get it wrong and there are also a lot of differences in browser support - jQuery handles all the quirks, so I don't have to worry about that.

Did you try the example I provided?

 
Dmitrij Jazel
Reply

No, not yet, but I think I give it a shot, now :)

I would have to adjust quite a bit in my Ajax login. Cause what I posted here, is simplyfied version of it...

 
Dmitrij Jazel
Reply

Hi Morten,

Your example works, but I can't parse the response.

}).done(function (data) {
        try {
            var response = JSON.parse(data);
            alert("response:" + response.toString());
            if (response.userstatus == "OK" && response.grantAccess == "True") {

As a response, I am getting an error - that most likely is caused by Razor error, but can't read it.

"Login ajax:SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data"

http://screencast.com/t/rP92RHfCpWN

I need a way to check whether login was successfull or not, in order to provide feedback.

Any suggestions?

/Dmitrij

 
Dmitrij Jazel
Reply

Ok, after some tryal and error, I found it, it was much I did not had to JSON parse data, I could just to straight for data.[attribute]

Thanks Morten! :)

 

You must be logged in to post in the forum