AngularJS $http provider not passing cookies to .NET Web Service - cookies

I am having problems using the $http provider in AngularJS to make an API call to a .NET backend that requires Authentication. The .NET backend service expects the ".ASPXAUTH" and "__RequestVerificationToken" cookies to be included in the call.
When I use plain JS and .ajax, passing the cookies in the beforesend block works.
$.ajax({
url: SERVER_URL + '/api/accounts',
type: 'GET',
dataType: 'json',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function(data, status){
// ...
},
error: function (request, textStatus, errorThrown) {
// ...
},
beforeSend: function (req) {
req.setRequestHeader("Cookie", REQUEST_VER_TOKEN);
req.setRequestHeader("Cookie", ASPXAUTH_TOKEN);
}
});
In AngularJS, I've tried setting it in the $httpProvider and in the $http call without success:
(in the config block):
// ...
app.config(function ($routeProvider, $httpProvider) {
$httpProvider.defaults.headers.common[".ASPXAUTH"] = '....';
$httpProvider.defaults.headers.common["__RequestVerificationToken"] = '....';
$httpProvider.defaults.useXDomain = true;
// ...
(in the $http call):
$http({ url: 'http://SERVER_URL/api/accounts', method: 'GET',
{headers: {
'__RequestVerificationToken': '....',
'.ASPXAUTH': '....'
}}
})
.success(function(data, status, headers, config) {
// ...
})
.error(function (data, status, headers, config) {
// ...
});
I get a 401 Unauthorised error. If the Authorization block is removed from the server code, the code works without needing to insert the headers. How do I emulate the same beforesend block in AngularJS and ensure that the cookies are passed to the server during the API call?

Did you try to pass your header parameters not in a json object but directly into the headers attribute?
$http({ url: 'http://SERVER_URL/api/accounts', method: 'GET',
headers: {
'__RequestVerificationToken': '....',
'.ASPXAUTH': '....'
}
}).success(function(data, status, headers, config) {
// ...
})
.error(function (data, status, headers, config) {
// ...
});
Hope it can help.

Related

Get data from one site collection into another site collection in same web application sharepoint 2016

I am using SharePoint 2016 on premise. I am having one web application in which i am having 2 site collections.
site 1 and site 2.
I want to show data from site collection 1 list on site collection 2 Page, using rest or java script or J query. My environment is not configured with apps so i can't use apps and even server side code as well.
Please suggest any alternatives for doing this.
Thanks in advance.
Share the script here in case someone have similar requirement.
<script>
$(function () {
getDataFromSite1();
getDataFromSite2();
})
function getDataFromSite1() {
var url = "http://sp:12001/_api/web/lists/GetByTitle('MyList')/items";
$.ajax({
async: false,
url: url,
method: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: function (data) {
console.log(data)
},
error: function (data) {
}
});
}
function getDataFromSite2() {
var url = "http://sp:12001/sites/team/_api/web/lists/GetByTitle('MyList')/items";
$.ajax({
async: false,
url: url,
method: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: function (data) {
console.log(data)
},
error: function (data) {
}
});
}
</script>

How to update the model from the ajax by rest framework(csrf problem??)

I want to update the table row by from ajax
From auto generated form (by rest framweorks) posting and updating works correctly.
However from ajax it shows
"POST /api/issues/372/ HTTP/1.1" 403 58 error
I googled around and found that this is related with csrt.
However How can I send correct json???
var json = {
"id": 37;
"name": "This is my new name",
"color": "#dddddd"
};
$.ajax({
type:"POST",
url: "{% url 'issues-detail' 372 %}",
data:JSON.stringify(json),
contentType: 'application/JSON',
dataType: "JSON",
success: function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
},
complete: function() {
console.log("complete");
}
});
you can add this code to your js file in document.ready function
$(document).ready(function() {
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url)))
{
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
}
}
});
});
For sending POST request we need to set csrf-token.

Laravel 5.6 Passport token in ajax

I was writing below code in Token Guard before using Passport authentication.
$.ajax({
method: "POST",
url: "{!! route('ViewProfile') !!}?api_token={!! \Auth::user()->api_token !!}",
cache: false,
async: true,
success: function(result) {
},
error: function(result) {
}
});
Now, I am changing my code to adapt Laravel Passport authentication. I have no problem in creating the token and fetching it using below code.
$token = $UserData->createToken(env("Token_Source_Website"))->accessToken;
Question: I was searching for a tutorial about how to send the ajax request to get user details using this token? I meant, will I use something else instead of api_token = somevalue?
It has to be like below. Make sure there is space after Bearer in headers.
$.ajax({
method: "POST",
url: "{!! route('ViewProfile') !!}?api_token={!! \Auth::user()->api_token !!}",
cache: false,
async: true,
headers: {"Authorization": "Bearer " + localStorage.getItem('token')},
success: function(result) {
},
error: function(result) {
}
});
One can get the token through below code.
$token = $UserData->createToken(env("Token_Source_Website"))->accessToken;

Create Item by using Item web api

I want to know how implement javascript method to create new item by using sitecore item web api.I am trying for below code my self.
But in the browser console show this error:
XMLHttpRequest cannot load http://myproject/-/item/v1/sitecore/Content/Home?name=MyItem5&template=Sample/Sample%20Item&sc_database=master. Request header field X-Scitemwebapi-Password is not allowed by Access-Control-Allow-Headers.
Please can anyone help me!!!!!!!
function createItem(){
jQuery.ajax({
crossDomain: 'true',
type: 'POST',
url: 'http://myproject/-/item/v1/sitecore/Content/Home?name=MyItem5&template=Sample/Sample Item&sc_database=master',
dataType: 'JSON',
contentType: 'application/x-www-form-urlencoded',
headers:{
"X-Scitemwebapi-Username":"sitecore\\Admin",
"X-Scitemwebapi-Password":"b",
},
success: function(data) {
alert(JSON.stringify(data));
},
error: function(res, error){
alert(JSON.stringify(res))
alert(res+ ' something is wrong');
}
});
}
Make sure you have these settings in your Sitecore.ItemWebApi.config
itemwebapi.mode="StandardSecurity"
itemwebapi.allowanonymousaccess="false"/>

How to call WCF Web Service (.svc) using jQuery

Hi I am trying to call a WCF web service(.svc)
$.ajax({
url: 'http://www.somedoamin.com/Services/service.svc',
dataType: "text/xml",
contentType:'text/xml; charset=utf-8',
beforeSend: function(xhr){
// Pass the soap action onto the proxy.
xhr.setRequestHeader(
"SOAPAction","http://www.anotherdomain.com/Services/Login"
);
},
data:soapMessage,
type: 'POST',
success: function(res) {
var myXML = res.responseText;
console.log('Response ',myXML);
},
error:function(jqXHR, textStatus, errorThrown,exception) {
console.log('An error occured ');
}
});
I am getting error callback. "An error occured"
So, Should i need to add some parameters to WCF Service ?
Refer this existing How Do I call A WCF Web Service from jQuery?
This is the solution they given
http://www.west-wind.com/weblog/posts/2008/Apr/21/jQuery-AJAX-calls-to-a-WCF-REST-Service