AJAX call with credentials

Hello I’m trying to get some data from a server, is ok to signin and get data in ajax, this is my code:

JS AJAX

// SIGNIN

$.ajax({
	url: WSROOT + "ethAccount.asmx/SignIn",
	data:  { email : email, password: pwd},
	success: function (retval, textStatus) { 
		console.log( JSON.stringify(retval));

	},
	error: function (xhr, textStatus, exception) {
		console.log("error");
	}
});

// FETCH DATA
$.ajax({
	url: WSROOT + "ethClient.asmx/GetTagList",
	type: "POST",
	contentType: "application/json; charset=utf-8",
	cache: false,
	dataType: "json",		
	xhrFields: { withCredentials: true },	
	success: function (retval, textStatus) {
		console.log( JSON.stringify(retval));
	}
});

I’m trying to do the same in fusetools:


//SIGNIN
var body = { "email" : "my@email.com", "password" : "mypass" };
fetch("https://www.mytaglist.com/ethAccount.asmx/SignIn", {
	method: 'post',
	body: JSON.stringify(body),
    headers: new Headers({ 'Content-Type': 'application/json' })	
  })
.then(function(response) { return response.json(); }) 
.then(function(responseObject) {  console.log(JSON.stringify(responseObject)); })
.catch(function(error){ console.log("Error: " + error); });		


//FETCH DATA

fetch( WSROOT + "ethClient.asmx/GetTagList", {
	method: 'post',
    headers: new Headers({ 
    	'Content-Type': 'application/json; charset=utf-8',
    	'cache': 'false',
    	'dataType': 'json',
    	'xhrFields': '{ withCredentials: true }',
    })
  })
.then(function(response) {  return response.json();  }) 
.then(function(responseObject) {  console.log(JSON.stringify(responseObject));})
.catch(function(error){ console.log("Error: " + error); });	

In fusetools I get the cookie but I don’t get data back afger the second call:

Output: {“Message”:“Authentication failed.”,“StackTrace”:null,“ExceptionType”:“System.InvalidOperationException”}

What am I doing wrong?, thanks.

Hi!

dataType, xhrFields and cache are settings specific to jQuery’s $.ajax() function, but you are trying to pass them as plain HTTP headers.
This is not going to work, since these options are, in fact not HTTP headers, but rather instructions for how to handle caching, cookies, and so on.

I’m not able to test it, but the following code should work:

fetch(WSROOT + "ethClient.asmx/GetTagList", {
    method: 'post',
    headers: { 
        'Content-Type': 'application/json; charset=utf-8'
    },
    cache: 'no-cache',
    credentials: 'include'
  })
.then(function(response) {  return response.json();  }) 
.then(function(responseObject) {  console.log(JSON.stringify(responseObject));})
.catch(function(error){ console.log("Error: " + error); });

Still not working, I get the following messages



console.log(JSON.stringify(response));
Output:	{"type":"default","responseObject":401,"ok":false,"statusText":"Unauthorized","headers":{"map":{"cache-control":["no-cache"],"pragma":["no-cache"],"content-type":["application/json; charset=utf-8"],"expires":["-1"],"server":["Microsoft-IIS/8.0"],"jsonerror":["true"],"date":["Tue, 18 Oct 2016 08:03:56 GMT"],"content-length":["105"]}},"url":"","_bodyInit":"{\"Message\":\"Authentication failed.\",\"StackTrace\":null,\"ExceptionType\":\"System.InvalidOperationException\"}","_bodyText":"{\"Message\":\"Authentication failed.\",\"StackTrace\":null,\"ExceptionType\":\"System.InvalidOperationException\"}"}

console.log(JSON.stringify(response));
Output:	{"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}


I looked into your issue, and unfortunately cookies are currently not persisted between calls to fetch().

You’ll have to work around this by parsing the Set-Cookie header sent by the server when logging in, and manually setting the Cookie header for all further requests belonging to that session.

I mocked up some code that might be useful as a starting point:

var authCookie;

function signIn() {
	var body = { "email" : "my@email.com", "password" : "mypass" };
	
	return fetch(WSROOT + "ethAccount.asmx/SignIn", {
		method: 'post',
		body: JSON.stringify(body),
		headers: new Headers({ 'Content-Type': 'application/json' })    
	})
	.then(function(response) {
		if(!response.headers.has("set-cookie")) {
			return Promise.reject("Did not receive cookie");
		}
		
		var cookieHeader = response.headers.get("set-cookie");
		
		// Warning: This is not a good way of extracting cookies,
		// use something along the lines of set-cookie-parser instead:
		// https://github.com/nfriedly/set-cookie-parser/blob/master/lib/set-cookie.js
		authCookie = cookieHeader.split(";")[0] + ";";
	});
}

function getTagList() {
	fetch(WSROOT + "ethClient.asmx/GetTagList", {
		method: 'post',
		headers: { 
			'Content-Type': 'application/json; charset=utf-8',
			'Cookie': authCookie // Use the authCookie we got from login()
		},
		cache: 'no-cache',
	})
	.then(function(response) { return response.json(); })
}

// Sign in and get tag list:

signIn()
    .then(getTagList)
    .then(function(tagList) {
        // Do something with tag list
    })
    .catch(function(err) { console.log(err); })

Awesome Sebastian!!, is working now.

Thank you very much.

Glad to hear it’s working :slight_smile: