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)
})
Related
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
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.
I tried angular.js and started with a web-ui for a restful api (using http basic auth). It is really nice and all except the authorization works.
Up to now I am using $http.defaults.headers.common.Authorization to set the password, but mostly the browser opens his default login-form for http-basic-auth. Another strange behaviour is that the angular-request does not contain a Authorisation-Header (neither OPTIONS nor the GET-request). I also tried to set this header on each request with the header-config, but this also didn't work.
Are there some special headers I have to set? Or do I have to set $http.defaults.headers.common.Authorization in a special context?
tools.factory('someFactory', function ($http, Base64) {
//...
factory.checkAuth = function (username, password) {
storeCredentials(username, password);
factory.initConnection();
return factory.getData();
};
factory.initConnection = function(){
var credentials = loadCredentials();
factory.authHeader = 'Basic ' + Base64.encode(credentials.username + ':' + credentials.password);
$http.defaults.headers.common.Authorization = factory.authHeader;
};
factory.getData = function () {
return $http({
method: 'GET',
url: urlBase + '/happening',
headers: {
// 'Authorization': factory.authHeader
}
});
};
Request header:
OPTIONS /v8/happening HTTP/1.1
Host: api.gospry.com
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://web.gospry.com
User-Agent: [..]
Access-Control-Request-Headers: accept, authorization
Accept: */*
Referer: http://web.gospry.com/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Response header:
The backend was slightly modified to support CORS (Access-Control-headers and preflight-request-support).
HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Access-Control-Allow-Origin: http://web.gospry.com
Access-Control-Allow-Methods: POST, GET, PUT, PUSH, OPTIONS, DELETE
Access-Control-Max-Age: 3600
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Authorization
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
Set-Cookie: JSESSIONID=2DDC92A1B0DC57C221CDC3B7A5DC1314; Path=/v8/; Secure; HttpOnly
WWW-Authenticate: Basic realm="Realm"
X-Content-Type-Options: nosniff
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length: 0
Date: Wed, 08 Apr 2015 18:04:04 GMT
I use an interceptor. I can't spot the issue in your code but here is what I am using:
authModule.factory('CeradAuthInterceptor',
['CeradAuthManager', function ( authManager)
{
return {
request: function (config)
{
config.headers = config.headers || {};
if (authManager.authToken)
{
config.headers.Authorization = 'Bearer ' + authManager.authToken;
}
return config;
}
};
}]);
appModule.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('CeradAuthInterceptor');
}]);
The issue you describe with the login-form is explained in the AngularJS Tips and Tricks Using ngResource with a workaround. See the Basic Authentication section:
A workaround, if appropriate, is to tell your web server to return something other than 401 on an authentication failure, and go from there. In AngularJS, a 500 (for example) will cause the $http promise to be rejected and you can handle it however you’d like. This is not recommended if you actually ever need the login prompt to occur!
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);
});
I'm trying to execute a POST throw the save method. Here is my model.
app.Models.Dummy = Backbone.Model.extend({
initialize: function () {
url = 'http://anotherdomain/Hello/';
},
});
When i execute:
dummy.save({text : "greg"}, {
success : function(){
console.log('Ok!');
},
error: function(){
console.log('Error');
}
});
The request is fired with an OPTIONS header (code 200) but the POST request is never fired.
However When i execute:
$.ajax({
type: 'POST',
url: "http://anotherdomain/Hello/",
data: {text:"greg"},
success: function(r) { alert(r.Result) },
dataType: "application/json"
});
it's works!
Does i need to override something in backbone?
EDIT:
The request is:
OPTIONS http://anotherdomain/Hello/ HTTP/1.1
Host: anotherdomain
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/17.0 Firefox/17.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Origin: http://mydomain
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Pragma: no-cache
Cache-Control: no-cache
and the response is:
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 0
Server: Microsoft-IIS/7.5
Set-Cookie: ARRAffinity=611c389e4fd6c5d83202b700ce5627f6e0850faf0604f13c25903b4662919f36;Path=/;Domain=anotherdomain
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Powered-By: ARR/2.5
X-Powered-By: ASP.NET
Date: Wed, 05 Dec 2012 18:44:27 GMT
That's not a valid OPTIONS response for CORS. The response needs to include headers that tell the browser what's allowed. For example (taken from MDN):
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER
I know you said that the $.ajax worked but based on this CORS response I doubt that is accurate and suggest you double check. Under the covers, backbone is itself just using $.ajax