Why cant i extract the cookie from the header? AngularJS + dJango - angularjs

Im trying to get the cookie value from the header but it returns undefined.
Using $cookies module.
Service:
socialMarkt.factory('homeService', ['$http', function($http){
var apiAddress = "http://server.apigoeshere.io:8000/s/first/";
return {
getEvents : function(params) {
return $http.get(apiAddress, {params});
}
}
}]);
Controller:
homeService.getEvents({"page":"1"}).then(
function(response){
$scope.events = response.data.events;
console.log($cookies.get('csrftoken')) //undefined;
});
Response Header
HTTP/1.1 200 OK
Server: gunicorn/19.4.5
Date: Tue, 01 Mar 2016 22:47:55 GMT
Connection: close
Transfer-Encoding: chunked
Vary: Cookie
X-Frame-Options: SAMEORIGIN
Content-Type: application/json
Set-Cookie: csrftoken=HN8Zqh7dup4DnnZInd25WT25DEQ3m5rM; expires=Tue, 28-Feb-2017 22:47:55 GMT; Max-Age=31449600; Path=/
Set-Cookie: sessionid=39aq2f5d06ianw65vgm3hmf37ctlbj3l; expires=Tue, 15-Mar-2016 22:47:55 GMT; httponly; Max-Age=1209600; Path=/
I cant get the csrftoken cookie. so i can use it to send post request on a django endpoint.

Related

How to make CORS origin call request from rally sdk (custom html code)?

I'm developing a custom html dashboard using the rally sdk and I want to populate one of the field data from a CORS origin request call.
Can you please provide some examples/links how to make CORS call using rally sdk custom html code?
I tried via ajax call it gives me 403 exception.
var usChangeSets = story.getCollection('Changesets');
console.log('usChangeSets--',usChangeSets);
usChangeSets.load({
fetch : ['Author', 'Message', 'Uri'],
callback: function(records, operation, success){
Ext.Array.each(records, function(changeset){
//Ajax api call to get details from external link
var blink ="https://[sonarqube]/job/Appdev/job/TestProject/api/json";
Ext.Ajax.request({
url: blink,
method :'GET',
crossDomain: true,
withCredentials: true,
headers : {
'Authorization': 'Basic dsasfsfxfhfj',
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin' : '*'
},
success: function(response){
var backToJs=JSON.parse(response.responseText);
console.log('resp data-',backToJs);
//console.log(backToJs['QueryResult'].Results);
},
failure: function(response) {
console.log('ajax call failure');
}
});
}
}
}
You need to configure your external server to allow CORS requests. The browser will automatically add the origin header to your request and then your server should respond with the appropriate cors headers (Access-Control-Allow-Origin).
Here's an example of how the rally server responds to a request from a different origin:
% http https://rally1.rallydev.com/slm/webservice/v2.0/testcaseresult/54277371431 zsessionid:_5507Kn8 origin:localhost -v
GET /slm/webservice/v2.0/testcaseresult/54277371431 HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: rally1.rallydev.com
User-Agent: HTTPie/0.9.9
origin: localhost
zsessionid: _55GAn8
HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: localhost
Access-Control-Expose-Headers:
CF-RAY: 38cbe03c4dd45005-DEN
Cache-Control: private,max-age=0,must-revalidate
Connection: keep-alive
Content-Encoding: gzip
Content-Length: 623
Content-Type: application/json; charset=utf-8
Date: Fri, 11 Aug 2017 14:27:29 GMT
ETag: "0b0e0cdae135fc6cd32fa496d7660c756"
Expires: Thu, 01 Jan 1970 00:00:00 GMT
P3P: CP="NON DSP COR CURa PSAa PSDa OUR NOR BUS PUR COM NAV STA"
RallyRequestID: qs-app-103xz471u80pea8opfovz9g8gv.qs-app-1014978663
Server: cloudflare-nginx
Set-Cookie: __cfduid=d604a6a0fa131613b997640ead95cc5171502461649; expires=Sat, 11-Aug-18 14:27:29 GMT; path=/; domain=.rallydev.com; HttpOnly
Set-Cookie: JSESSIONID=qs-a0;Path=/;Secure;HttpOnly
Set-Cookie: SUBBUCKETID=209;Path=/;Domain=rally1.rallydev.com;Secure;HttpOnly
Set-Cookie: SUBSCRIPTIONID=209;Path=/;Domain=rally1.rallydev.com;Secure;HttpOnly
Set-Cookie: SERVERID=319fca23748f5704e88bd8741ae60476b188cf5e; path=/
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload;
Vary: Accept-Encoding
X-XSS-Protection: 1; mode=block

cookies in angular $http post requests

I'm connecting to some non documented apis using angular $http requests in a ionic app.
I have two different apis I use and both of them use Set-Cookie, one of them works fine without me having to pick certain cookies for the calls or even use cookie headers in the $http posts.
But not in the other one, that gives me multiple Set-Cookies and only use some of them for the next calls, is there some way I can see what cookies that are sent in my $http post or see what cookies that are stored or something like that?
my guess is I'm not sending the right one's, the only difference from my rest-client "where it works" is that in angular I don't know what cookies I'm sending..
EDIT
Here is the response I'm getting which include the coookies I need for another call
HTTP/1.1 200 OK
content-type: text/plain
date: Wed, 23 Sep 2015 20:39:38 GMT
cache-control: private
sebstatus: 200
expires: Wed, 23 Sep 2015 20:38:38 GMT
sebstatusmessage: OK: status=Success errorCode= errorMessage=
Set-Cookie: WM7NET=4bap4pcjijvoqgpi153daxmv;Secure; Path=/
Set-Cookie: WM7NET=4bap4pcjijvoqgpi153daxmv; Path=/
Set-Cookie: WM7=osTkv3IzxAlK5WApfphBw1Tko3OVS0;Secure; Path=/
Set-Cookie: iampsc1110=rd520o00000000000000000000ffff0a101fa2o1110;secure; path=/
Set-Cookie: TSaee27a=884dc16339c369b257519e459c177d77a0094933039a35c356030e0a3b92707026ec4c7f3b92707026ec4c7fed2d4e69f9e16a0af3fdf509a27e412a; Path=/
Set-Cookie: avr_1380360832_0_0_4294901760_2725612627_2=1875832750_21493071;max- age=300;path=/
Vary: Accept-Encoding
Content-Encoding: gzip
Transfer-Encoding: chunked
Connection: Keep-alive
and here is the call I'm doing to the next step.
var data = {'SB_Referer': '/priv/ServiceFactory-mbid'}
$http({
withCredentials: true,
url: 'https://mp.example.se/nauth2/Authentication/Auth?SB_Referer=/priv/ServiceFactory-mbid',
method: 'POST',
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
// console.log('string is', str)
return str.join("&");
},
data: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'SB-Prkund/6.1.3 CFNetwork/672.1.14 Darwin/14.0.0',
'Proxy-Connection': 'keep-alive',
'Accept-Language': 'sv-se',
'Accept-Encoding': 'gzip, deflate',
'Content-Length': 0,
}
}).then(function(response){
console.log(JSON.stringify(response.data), response.status, response.headers('Set-Cookie'), response.config)
})

Elgg Headers in http request not allowed

I am developing a frontend application in AngularJS, an i'am trying to login in a elgg platform.
As described in the documentation here if you want to use HMAC auth, you have to add some custom headers. And in AngularJS I have used interceptors.
$httpProvider.interceptors.push(function($q, HMAC){
return {
// optional method
'request': function(config) {
// do something on success
console.log("Interceptor Config-> ",config);
console.log("HTTP? --> ",config.url.indexOf('http'));
if(config.url.indexOf('http') == 0){
//do something only on http requests
config.headers = config.headers || {};
config.headers['X-Elgg-apikey'] = "";
config.headers['X-Elgg-time'] = "";
config.headers['X-Elgg-none'] = "";
config.headers['X-Elgg-hmac'] = "";
config.headers['X-Elgg-hmac-algo'] = "";
}
console.log("Return -->", config);
return config || $q.when(config);
}
};
});
But the response the response i got is :
XMLHttpRequest cannot load http://localhost/elgg-1.9.8/elgg-1.9.8/services/api/rest/xml/?method=auth.gettoken.
Request header field X- Elgg-hmac-algo is not allowed by Access-Control-Allow-Headers.
I have apache on my webserver on localhost and i have configured :
<Directory />
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Request-Headers "*"
Header always set Access-Control-Request-Method "*"
AllowOverride none
Require all denied
</Directory>
I have also checked the response header and this what i got :
HTTP/1.1 200 OK
Date: Sat, 30 May 2015 13:37:07 GMT
Server: Apache/2.4.10 (Unix) OpenSSL/1.0.1j PHP/5.6.3 mod_perl/2.0.8-dev Perl/v5.16.3
Access-Control-Allow-Origin: *
Access-Control-Request-Headers: *
Access-Control-Request-Method: *
X-Powered-By: PHP/5.6.3
Cache-Control: no-cache, must-revalidate
Expires: Fri, 05 Feb 1982 00:00:00 -0500
Vary: Accept-Encoding,User-Agent
Content-Encoding: gzip
Content-Length: 81
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
I can't find where is the bug. I setted the headers response on the server but i still got this error on console.
Thanks

Required Parameter is missing grant_type Google oauth2.0 AngularJS and Cordova inappbrowser

I am using Cordova's inappbrowser and integrating Google oauth2.0. Once I get the authorization code I make a post request to get my token. NO MATTER what I try I always get a 400 error with "Required Parameter is missing grant_type". I'm encoding uri, I'm setting the right headers but to no avail... can anyone help?
$http({
method: 'POST',
url: 'https://accounts.google.com/o/oauth2/token',
params:{code:authorization_code[0],
client_id:options.client_id,
client_secret:options.client_secret,
redirect_uri:options.redirect_uri,
grant_type:'authorization_code'},
headers:{
'Content-Type':'application/x-www-form-urlencoded',
}
}).success(function(data,status,headers,config){
deferred.resolve(data);
}).error(function(data, status,headers,config){
console.log('data, status, headers,config',data,status,headers,config);
deferred.reject(response.responseJSON);
});
and this is the output from the Chrome dev Console when I try to make the request
Request URL:https://accounts.google.com/o/oauth2/token?client_id=736406995874-oh7o4cmaju3jgprllln97nf0p3pc1f91.apps.googleusercontent.com&client_secret=ysgrIV6mJXxritfXnRcclV_U&code=4%2FnITDK731NhavPePthrVA1eX8LHFC.ojUX9K7DpBYaEnp6UAPFm0HWDS5njgI&grant_type=authorization_code&redirect_uri=http:%2F%2Flocalhost
Request Method:POST
Status Code:400 Bad Request
Request Headers
POST https://accounts.google.com/o/oauth2/token?client_id=xxx-oh7o4cmaju3jgprllln97nf0p3pc1f91.apps.googleusercontent.com&client_secret=xxx&code=4%2FnITDK731NhavPePthrVA1eX8LHFC.ojUX9K7DpBYaEnp6UAPFm0HWDS5njgI&grant_type=authorization_code&redirect_uri=http:%2F%2Flocalhost HTTP/1.1
Accept: application/json, text/plain, /
Origin: file://
testing: testing
User-Agent: Mozilla/5.0 (Linux; Android 4.4.2; SCH-I535 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36
Query String Parameters
client_id=xxx-oh7o4cmaju3jgprllln97nf0p3pc1f91.apps.googleusercontent.com&client_secret=xxx&code=4%2FnITDK731NhavPePthrVA1eX8LHFC.ojUX9K7DpBYaEnp6UAPFm0HWDS5njgI&grant_type=authorization_code&redirect_uri=http:%2F%2Flocalhost
Response Headers
HTTP/1.1 400 Bad Request
Pragma: no-cache
Date: Mon, 14 Jul 2014 06:35:22 GMT
Content-Encoding: gzip
X-Content-Type-Options: nosniff
Server: GSE
X-Frame-Options: SAMEORIGIN
Content-Type: application/json
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Transfer-Encoding: chunked
Alternate-Protocol: 443:quic
X-XSS-Protection: 1; mode=block
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Wrong post request. The params property is used to set any additional request parameters to be appended to the URL query string. The params property is a JavaScript object with one property per request parameter to add.
Here for your reference.
You just need to send data/params in serialized (for angular use $httpParamSerializer)
$http({
method: 'POST',
url: 'https://accounts.google.com/o/oauth2/token',
params:$httpParamSerializer({code:authorization_code[0],
client_id:options.client_id,
client_secret:options.client_secret,
redirect_uri:options.redirect_uri,
grant_type:'authorization_code'}),
headers:{
'Content-Type':'application/x-www-form-urlencoded',
}
}).success(function(data,status,headers,config){
deferred.resolve(data);
}).error(function(data, status,headers,config){
console.log('data, status, headers,config',data,status,headers,config);
deferred.reject(response.responseJSON);
});

error fetching backbone model (works in chrome but not in firefox and ie9)

I have one service that returns proper data in chrome but ends in error for firefox and ie9. It looks like the GET returns 200 OK code, but still ends in error callback. I'm fetching data via backbonejs (with jquery.getJson and with ajax I'm getting the same result). The same result I'm getting also if I try to fetch data from remote server or locally.
Chrome: Version 23.0.1271.64 m
FF: 16.0.2
IE9: 9.0.8112.16421
wcf:
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/getData/{name}", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
List<Names> getData(string name);
serviceUrl:
"http://serverABC:4000/myService.svc/getData/test"
fetching from javascript:
via backbone or jqueryGetJson():
$.getJSON("http://serverABC:4000/myService.svc/getData/test", function () {
alert("success");
})
.success(function () { alert("second success"); })
.error(function (result) {
console.log('error:', result);
})
result:
"http://serverABC:4000/myService.svc/getData/test 200 OK 70ms"
headers:
Response Headers
Cache-Control private
Content-Length 6544
Content-Type application/json; charset=utf-8
Date Fri, 16 Nov 2012 14:09:46 GMT
Server Microsoft-IIS/7.5
Set-Cookie ASP.NET_SessionId=s3aguluzip0dw135glbxlwwf; path=/; HttpOnly
X-AspNet-Version 4.0.30319
X-Powered-By ASP.NET
Request Headers
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection keep-alive
Host svgwbip93:4000
Origin http://localhost:51280
Referer http://localhost:51280/Default.aspx?ReturnUrl=%2f
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0
result from debug:
readyState 0
responseText ""
status 0
**statusText "error"**
abort function()
always function()
complete function()
done function()
error function()
fail function()
getAllResponseHeaders function()
getResponseHeader function()
overrideMimeType function()
pipe function()
progress function()
promise function()
setRequestHeader function()
state function()
statusCode function()
success function()
then function()
toString function()
Response: - is empty (this is most probably the problem (but as I mentioned in Chrome I'm getting correct json data)
EDIT 1:
I tried to get raw response with fiddler and I'm getting the JSON. The big question is that why callback falls to error.
Here is my raw response:
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 29
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
Set-Cookie: ASP.NET_SessionId=kuv3g0r2dgmu5bpaoayj5lic; path=/; HttpOnly
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 16 Nov 2012 19:32:58 GMT
{"PlatformDrawingsResult":[]}
I verified the json - it seems OK, so what can be the problem....hmm. I forgot to mention that I'm using also requirejs (not sure if that will bring some light,..)
Cheers, Miro
The solution is (thanks to jwkeenan) :
I put this line at the beggining of each method in my web service and
now all browsers work.
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
and to get it to work in ie9 I needed to add this to my web app:
$.support.cors = true;

Resources