Angularjs send only JSESSIONID cookie not others - angularjs

We are working on a RESTful Webservice with AngularJS.
We are invoking Restful web service which create a cookie using addCookie() method of javax.servlet.http.HttpServletResponse (yes before that do some business processing). Once the response is returned from web service
We can see the cookie under Set-Cookie element of Response headers. Please look into Response from browser developer tool.
Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/test-app/authCode/activate
Request Method:POST
Status Code:200 OK
Response Headers
Content-Length:0
Date:Tue, 26 May 2015 14:41:33 GMT
message:System activated the authorization code provided
Server:Apache-Coyote/1.1
Set-Cookie:auth_cookie_name=VckfCE; Expires=Tue, 26-May-2015 20:41:33 GMT; Path=/services
success:true
Request Headers
Accept:application/json, text/plain, /
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:6
Content-Type:application/json
Cookie:JSESSIONID=A61316520C343254790F12AE03D13242
Host:localhost:8080
Referer:http://localhost:8080/test-app/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36
Request Payload
VckfCE
After that we navigate to other resource using angularjs $location.path('/resource'). When this call get executed control goes to a javax.servlet.Filter and we try to read cookie 'auth_cookie_name' using request.getCookies() but only JSESSIONID cookie is found there not 'auth_cookie_name'.
How can I enable AngularJS to send this cookies?

Your cookie response
Cookie:auth_cookie_name=VckfCE; Expires=Tue, 26-May-2015 20:41:33 GMT; Path=/services
has Path option and this cookie is limited to this prefix.
As a result "auth_cookie_name" is not sent in $location.path('/resource'), because "/resource" doesn't start with "services".

Related

Too many OPTIONS requests

In my application, the front end (ReactJS using axios, if that matters) makes some API calls to the backend (Node/Express, again if that matters). In all of the responses, server does responds with Access-Control-Allow-Origin:* (This is a test environment, appropriate changes will be made to allow specific origins in production).
In the Chrome Developer Tools Network tab, I observe that for every request say POST /assets , POST /filters, PUT /media etc., a preflighted OPTIONS request is sent. Now I do understand from here, the reason for those and that's fine.
OPTIONS Request Headers
OPTIONS /api/v1/content/bb54fbf52909f78e015f/f91659797e93cba7ae9b/asset/all
HTTP/1.1
Host: XX.X.XX.XXX:5000
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
Access-Control-Request-Headers: authorization,content-type
Accept: */*
DNT: 1
Referer: http://localhost:3000/main/93f1ced0f15f35024402/assets
Accept-Encoding: gzip, deflate
Accept-Language: en,en-US;q=0.8,mr;q=0.6
Response Headers
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Vary: Access-Control-Request-Headers
Access-Control-Allow-Headers: authorization,content-type
Date: Sat, 05 Aug 2017 10:09:16 GMT
Connection: keep-alive
My observation is that this is sent for literally every requests, and repetitively i.e. even if the same request is being made again (immediately or otherwise).
My questions are
Is this necessarily a bad thing (i.e. would it cause any performance issues, even minor)?
Why doesn't browser remember the header responses for the same server, same request?
Is there anything I am missing to configure on the front end or backend for making this sticky?
You need to send the Access-Control-Max-Age header to tell the browser that it’s OK to cache your other Access-Control-* headers for that many seconds:
Access-Control-Max-Age: 600

How to get the custom header values in the angular application when application open

I have Angular application A, that will open by other application B, while opening application by B, they will send one attribute in the request header, how can i accesses, that custom header in my angular application when its opening, the custom header i can seen tcpdump.
Below is the header, i want accesses 'acbd' value
Connection: keep-alive
Referer:
User-Agent: Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; HTC Desire Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30
Accept-Encoding: gzip,deflate
Accept-Language: en-US
Accept-Charset: utf-8, iso-8859-1, utf-16, *;q=0.7
Cookie: NG_TRANSLATE_LANG_KEY=%22en%22
**abcd: 13223223**
Http headers are not accesible via Javascript (only http-referer and http-user-agent via object properties, and http-cookie). If you need to pass some value from one application to another, you can use cookies and retrieve value parsing document.cookie variable.
Edit: Headers can be accessed via XmlHttpRequest object when using Ajax requests, but only restricted to simple response headers, and additional restrictions by CORS if your request is cross-domain. Some cookies marked as Http-only cannot be accessed via Javascript.

Updating of a custom req.session property value does not seem to persist quick enough

I have some Express middleware handling GET requests from my client side application to make subsequent requests to a separate API server that uses OAuth2 tokens, I am also using express-session for the storage of these tokens.
In my middleware that makes the outgoing request I have added handling to cope with occasions where an access token expires (API server sends back a 403) and makes a request to refresh the tokens, after which it will then issue the same original outgoing request to the API server, so the client is unaware of this all going on. The new tokens retrieved are then persisted back to the session store via express-session for use in subsequent requests. The tokens are also used for setting a Authorization bearer token header as you will see further below.
Here's the parts of my Express code that's involved:
routes.controller.js
//Currently handling GET API requests from client
module.exports.fetch = function(req, res) {
var options = helpers.buildAPIRequestOptions(req);
helpers.performOutgoingRequest(req, res, options);
};
helpers.js
module.exports.buildAPIRequestOptions = function(req, url) {
var options = {};
options.method = req.method;
options.uri = 'http://someurl.com' + req.path;
options.qs = req.query;
options.headers = {
'Authorization': 'Bearer ' + req.session.accessToken
};
return options;
};
module.exports.performOutgoingRequest = function(req, res, options) {
request(options, function(err, response, body){
if(response.statusCode === 401){
console.log(chalk.red('\n--- 401 RESPONSE RECEIVED TRY REFRESHING TOKENS ---'));
//Note the third param to call below is a callback and is invoked when calling next() in the refreshToken middleware
authController.refreshToken(req, res, function(){
console.log(chalk.green('\n--- RETRYING ORIGINAL REQUEST WITH UPDATED ACCESS TOKEN ---'));
//Re-use original request options, but making sure we update the Authorization header beforehand
options.headers.Authorization = 'Bearer ' + req.session.accessToken;
retryOutgoingRequest(res, options);
});
} else {
res.status(response.statusCode).send(body);
}
});
};
function retryOutgoingRequest(res, options) {
request(options, function(err, response, body){
if(err) {
console.log(err);
}
res.status(response.statusCode).send(body);
});
};
auth.controller.js
module.exports.refreshToken = function(req, res, next) {
var formData = {
grant_type: 'refresh_token',
refresh_token: req.session.refreshToken
},
headers = {
'Authorization' : 'Basic ' + consts.CLIENT_KEY_SECRET_BASE64
};
request.post({url:consts.ACCESS_TOKEN_REQUEST_URL, form:formData, headers: headers, rejectUnauthorized: false}, function(err, response, body){
var responseBody = JSON.parse(body);
if (response.statusCode === 200) {
req.session.accessToken = responseBody.access_token;
req.session.refreshToken = responseBody.refresh_token;
next();
} else {
console.log(chalk.yellow('A problem occurred refreshing tokens, sending 401 HTTP response back to client...'));
res.status(401).send();
}
});
};
For the most part the above is working just fine
When a user first log's in, some additional user profile info is fetched from the API server before they are taken to the main page of the application.
Some of the pages in the application also fetch data on page load, and so are subject to the access token checks.
During normal usage, so when a user logs in, and starts clicking around the pages, I can see the tokens are getting swapped out and saved in the session store via express-session as and when they expire. The new access token is correctly being used for subsequent requests as per the middleware I have written.
I now have a scenario where my middleware does not work.
So say I'm on a page that loads data on page load, lets say its an orders page. If I wait until the configured token expiry time on the API server has passed and then refresh the browser, the client side app will first make a request for the user info, and on success will then request the orders data required for the page (using AngularJS promises)
In my Express app the user info request gets a 403 from API server and so the tokens get refreshed via my middleware above, and the req.session.accessToken gets updated which I can see through console logging in my server application. But the next fetch of data for the orders ends up using the previously set access token and this causes a further unauthorised error from the API server since a request is being made with an invalid token.
If I refresh the browser again, both the user info and orders are fetched using the correct updated token from the previous middleware flow.
So I'm unsure what's going on here, I'm wondering if it's a timing issue with the req.session object not being persisted back to the session store in time for the next request to pick up?
Anyone got any ideas what may be going on here?
Thanks
Update 1
As requested in the comments, here are the request and response headers for the two requests being made.
First Request (which uses updated token server side)
Request Headers
GET /api/userinfo HTTP/1.1
Host: localhost:5000
Connection: keep-alive
Accept: application/json, text/plain, */*
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36
Referer: https://localhost:5000/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Cookie: interact.sid=s%3A0NDG_bn67NeGQAYl1wP1-TmM19ExavFm.Zjv65e9BtSyNBuo%2FDxZEk2Np0963frVur4zHyYw3y5I
Response Headers
HTTP/1.1 200 OK
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=86400
X-Download-Options: noopen
X-XSS-Protection: 1; mode=block
Content-Type: text/html; charset=utf-8
Content-Length: 364
ETag: W/"16c-4AIbpZmTm3I+Yl+SbZdirw"
set-cookie: interact.sid=s%3A0NDG_bn67NeGQAYl1wP1-TmM19ExavFm.Zjv65e9BtSyNBuo%2FDxZEk2Np0963frVur4zHyYw3y5I; Path=/; Expires=Fri, 13 May 2016 11:54:56 GMT; HttpOnly; Secure
Date: Fri, 13 May 2016 11:24:56 GMT
Connection: keep-alive
Second Request (which uses old token server side)
Request Headers
GET /api/customers HTTP/1.1
Host: localhost:5000
Connection: keep-alive
Accept: application/json, text/plain, */*
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36
Referer: https://localhost:5000/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Cookie: interact.sid=s%3A0NDG_bn67NeGQAYl1wP1-TmM19ExavFm.Zjv65e9BtSyNBuo%2FDxZEk2Np0963frVur4zHyYw3y5I
Response Headers
HTTP/1.1 401 Unauthorized
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=86400
X-Download-Options: noopen
X-XSS-Protection: 1; mode=block
set-cookie: interact.sid=s%3A0NDG_bn67NeGQAYl1wP1-TmM19ExavFm.Zjv65e9BtSyNBuo%2FDxZEk2Np0963frVur4zHyYw3y5I; Path=/; Expires=Fri, 13 May 2016 11:54:56 GMT; HttpOnly; Secure
Date: Fri, 13 May 2016 11:24:56 GMT
Connection: keep-alive
Content-Length: 0
Update 2
I should also mention I am using connect-mongo for my session store, I have tried using the default memory store but the same behaviour exists.
it sounds like a race condition client side, if you are performing 2 requests (to check auth - and then get data) is the second (get data) nested into the first calls success? or are you calling both at the same time linearly?
my thought is:
client - sends user info request (sessionid 1) - server processing
client - gets order info request (sessionid 1) - server processing
server - responds user info - 403 - client updates session id
server - responds order info - 403
really what you want is:
client - sends user info request (session 1) - server processing
server - gets user info request (403) - client updates session id
client - gets order info request (session 2) - server processing
server - respondes order info - actual results

Why does Salesforce OAuth2 redirect me from one instance na3 for ex to another na9

I am trying to build a web app that lets the customer add demo data to any Salesforce instance. My demo builder uses OAuth 2 Authorization Code Grant.
I am trying to get the switch instance portion working. However once the user connects to one instance
GET /services/oauth2/authorize?response_type=code&client_id=blabla.UKP&redirect_uri=https%3A%2F%2Fsfblademo.bla.com%2Foauth%2Fcallback HTTP/1.1
Host: na9.salesforce.com
Connection: keep-alive
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.12 Safari/535.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: cookie_bla; disco=5:00D50000000Ii39:00550000001ifEp:0|; autocomplete=1; inst=APP5
It redirects to the previous instance. Seems like its reading cookies and redirecting
HTTP/1.1 302 Found
Server:
Location: https://na3.salesforce.com/setup/secur/RemoteAccessAuthorizationPage.apexp?source=blablabla
Content-Type: text/html
Content-Length: 525
Date: Fri, 16 Sep 2011 21:46:58 GMT
The URL has moved here
Is there a way to sign out or clear the cookies salesforce has. I am not running my app on salesforce.
Thanks !
The API logout() call isn't going to work because that will only invalidate the API session and not the UI session stored in the browser cookie on the *.salesforce.com domain, to which your app won't have direct access. That's not to say it isn't still recommended, but to clear that UI cookie, you'll need to redirect the end user to /secur/logout.jsp on the instance_url of the previous session. To make it transparent to end users, you can load it in a hidden iframe like this:
<iframe src='https://{instance_url}/secur/logout.jsp' width='0' height='0' style='display:none;'></iframe>
Before switching to other instance, you can try making the logout call, as described here WS Guide :http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_logout.htm
This will invalidate the previous session hopefully..

Google Mobile Ads in Win Phone 7 Applications

I'm interested in using Google Ads in my Win Phone 7 Application. I've created a custom control that currently uses AdMob services to load ads, and I'm interested in incorporating a Google Ads provider (as well as any others I can). You can see the source for this control here: https://bitbucket.org/jacob4u2/moads/wiki/Home.
The best case scenario for me would be information about some kind of REST based JSON service that I could call and get back information like; Image Url, Ad Text, Ad Link Url. I've already done some research with the javascript that is added to a website that calls out to such a service to get ads, I would just like to know the legality and possibility of using this underlying service for myself.
Here's a look at the underlying service request and response from the Google Mobile Website Ad Sense Javascript from Fiddler:
GET http://googleads.g.doubleclick.net/pagead/ads?oe=utf8&ad_type=text_image&client=[someclientstring]&color_bg=FFFFFF&color_border=336699&color_link=0000FF&color_text=000000&color_url=008000&correlator=1283032525791&dt=1283032525791&ea=0&flash=0&format=320x50_mb&frm=1&js=afmc-v1.1&output=html&u_ah=738&u_aw=1366&u_cd=32&u_h=768&u_w=1366&u_his=1&u_tz=-240&url=http%3A%2F%2Flocalhost%3A53339%2F&dtd=5 HTTP/1.1
Host: googleads.g.doubleclick.net
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.127 Safari/533.4
Referer: http://localhost:53339/
Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: __gads=ID=2ca5d68be0ad9c24:T=1276802611:S=ALNI_Mb20Pe5DhybgSn6XMox3s10fBFcgw; VWCUK200=L070410/Q46888_8658_5_070410_2_123110_188666x187920x070410x1x2/Q46885_8658_5_062810_1_123110_188672x187926x062910x1x1; id=ca99132260000f4|1782317/496326/14815|t=1272328868|et=730|cs=w4txjauw
HTTP/1.1 200 OK
P3P: policyref="http://googleads.g.doubleclick.net/pagead/gcn_p3p_.xml", CP="CURa ADMa DEVa TAIo PSAo PSDo OUR IND UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"
Content-Type: text/html; charset=UTF-8
X-Content-Type-Options: nosniff
Date: Sat, 28 Aug 2010 21:54:25 GMT
Server: cafe
Cache-Control: private, x-gzip-ok=""
Content-Length: 603
X-XSS-Protection: 1; mode=block
<html><body style="background-color:transparent"></body></html>
Looks like a lot of parameters, hopefully I've removed any confidential stuff. Anyone ever looked into anything like this?
I would contact Google to see if this is within their terms of service - it would be a shame to do the coding and then find out that that you get no revenue from them.
I would also consider how the ads are chosen if this is not a web page. Typically the ads are chosen base don the page context. In Silverlight apps on the phone there is no web page context.

Resources