share cookies between subdomains using express/angularjs - angularjs

I've been trying to accomplish this task for quite some time but haven't got any breakthrough yet. I would be really thankful if anyone can help me out in this.
Current Situation:
I've two applications that I'm running in two sub-domains as
st.localhost:8080 and acm.localhost:8080
When a user tries to access either of the URLs, I search for a cookie named 'auth' using Angular $cookies service. If the cookie is defined or present, the user is redirected to original application. However, if the cookie is undefined, user is redirected to a login page(the login page resides in both the applications).
From the login page, after successful credentials check, I set the 'auth' cookie again with a random value. This cookie is supposed to be shared between the two sub-domains.
Express:
var express = require('express');
var httpProxy = require('http-proxy');
var vhost = require('vhost');
var app = express();
var proxy = httpProxy.createProxyServer();
app.get('/login', function(req, res) {
var randomNumber=Math.random().toString();
randomNumber=randomNumber.substring(2,randomNumber.length);
var expireDate = new Date();
expireDate.setDate(expireDate.getDate() + 1);
res.cookie('auth', randomNumber, { maxAge: 90000000, domain: 'localhost', httpOnly: false });
console.log('cookie created successfully');
res.send('Login successful');
});
app.use('/api', function(req, res) {
req.headers[ 'Authorization' ] = 'Basic dXNlcjpwYXNzd29yZA==';
console.log("Request cookies: " + req.cookie);
proxy.web(req, res, { target: 'restApiTarget' });
});
// ST application
app.use(vhost('st.localhost', express.static('./st')));
// ACM application
app.use(vhost('acm.localhost', express.static('./acm')));
app.listen(8080, function () {
console.log('Fweb server running on port 8080!');
});
Angular
Below login function is shared by both ST and ACM applications
$scope.login = function(formValid){
$scope.incorrectCredentials = false;
if(formValid){
$http.get('/login',
{
params: {
username: $scope.username,
password: $scope.password
},
headers : {
'Accept' : 'application/json'
}
}
).then(function(response){
$scope.incorrectCredentials = false;
var obj = $cookies.getObject('auth');
console.log("auth is: " + obj);
$state.go($stateParams.origin);
}, function(response){
$scope.incorrectCredentials = true;
});
}
}
Express is able to successfully create the cookie 'auth' as I can see the Set-Cookie header in the /login service response. However, the browser is not attaching this cookie to the subsequent API requests that I'm making from my application(say st.localhost). I'm not able to read this cookie through Angular as well.
var obj = $cookies.getObject('auth');
console.log("auth is: " + obj);
results in obj being undefined.
I've a feeling that there is something wrong in the way I'm setting the domain of the cookie as 'localhost' from one of the sub-domains.
Any suggestions on what I may be doing wrong?
Thanks in advance.

This is the second time I'm providing an answer to my own question. I guess I need to be more patient next time onwards before posting a question. Anyways, I hope this answer is helpful for people who are stuck in a similar situation like I was.
Firstly, I found out that it is possible to share a cookie between subdomains even if you create it in one of the subdomains. However, there were some posts/answers which said otherwise.
What one needs to do while creating a cookie in one of the subdomains is that the parameter 'domain' needs to be set as the parent domain value. For example, if you are creating a cookie in say st.testserver.com then while setting a sharable cookie in it, the 'domain' parameter must be set as '.testserver'.
However, if your parent domain is also the Top Level Domain(TLD), then you won't be able to create a shared cookie in the subdomain. This is exactly what was happening to me earlier when I posted this question.
When I was using st.localhost and trying to create a cookie with 'domain' as '.localhost', it wasn't allowing me to do so because localhost here is the TLD. But when I renamed my domain name to st.testserver.com, I was able to create the cookie with 'domain' as '.testserver.com' because it wasn't the TLD anymore.
I hope someone can validate this answer once and let me know if I provided any incorrect information.
Thanks.

Cookies is domain specific , if you want access across domain, you need to use some cross store like cross-storage etc.

Related

Asynchronously Respond in new Hangout Chat using rest API, without using google app engine

How can I post message as a bot(async) in new hangouts chat without using the Google App Engine. I have gone through the examples, but all of them use App Engine for authentication, but i need to authenticate it without using the same.
Here is a code sample that connects to a chat using an http request and a webhook from Google Hangout Chat with a Python script. Webhooks are the only alternative to using a service account. More info here: https://developers.google.com/hangouts/chat/how-tos/webhooks
`from httplib2 import Http
from json import dumps
#
# Hangouts Chat incoming webhook quickstart
#
def main():
url = '<webhook url here>'
bot_message = {
'text' : 'text go here'}
message_headers = { 'Content-Type': 'application/json; charset=UTF-8'}
http_obj = Http()
response = http_obj.request(
uri=url,
method='POST',
headers=message_headers,
body=dumps(bot_message),
)
print(response)
if __name__ == '__main__':
main()
`
If your bot implementation is with google app script try to do it with google service account and as indicated here an example of async message
// Example bot for Hangouts Chat that demonstrates bot-initiated messages
// by spamming the user every minute.
//
// This bot makes use of the Apps Script OAuth2 library at:
// https://github.com/googlesamples/apps-script-oauth2
//
// Follow the instructions there to add the library to your script.
// When added to a space, we store the space's ID in ScriptProperties.
function onAddToSpace(e) {
PropertiesService.getScriptProperties()
.setProperty(e.space.name, '');
return {
'text': 'Hi! I\'ll post a message here every minute. ' +
'Please remove me after testing or I\'ll keep spamming you!'
};
}
// When removed from a space, we remove the space's ID from ScriptProperties.
function onRemoveFromSpace(e) {
PropertiesService.getScriptProperties()
.deleteProperty(e.space.name);
}
// Add a trigger that invokes this function every minute via the
// "Edit > Current Project's Triggers" menu. When it runs, it will
// post in each space the bot was added to.
function onTrigger() {
var spaceIds = PropertiesService.getScriptProperties()
.getKeys();
var message = { 'text': 'Hi! It\'s now ' + (new Date()) };
for (var i = 0; i < spaceIds.length; ++i) {
postMessage(spaceIds[i], message);
}
}
var SCOPE = 'https://www.googleapis.com/auth/chat.bot';
// The values below are copied from the JSON file downloaded upon
// service account creation.
var SERVICE_ACCOUNT_PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n';
var SERVICE_ACCOUNT_EMAIL = 'service-account#project-id.iam.gserviceaccount.com';
// Posts a message into the given space ID via the API, using
// service account authentication.
function postMessage(spaceId, message) {
var service = OAuth2.createService('chat')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setPrivateKey(SERVICE_ACCOUNT_PRIVATE_KEY)
.setClientId(SERVICE_ACCOUNT_EMAIL)
.setPropertyStore(PropertiesService.getUserProperties())
.setScope(SCOPE);
if (!service.hasAccess()) {
Logger.log('Authentication error: %s', service.getLastError());
return;
}
var url = 'https://chat.googleapis.com/v1/' + spaceId + '/messages';
UrlFetchApp.fetch(url, {
method: 'post',
headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
contentType: 'application/json',
payload: JSON.stringify(message),
});
}
You need to perform some below steps.
Create a service-account in console.developers.google.com and download the private key in JSON format
Use below modules if you code in python.
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build, build_from_document
from httplib2 import Http
Below snippet will post the message to user via chat.google.
scopes = ['https://www.googleapis.com/auth/chat.bot']
credentials = ServiceAccountCredentials.from_json_keyfile_name('/path/to/json',
scopes)
http = Http()
credentials.authorize(http)
chat = build('chat', 'v1', http=http)
resp = chat.spaces().messages().create(
parent=space,
body={'text': 'HELLO WORLD'}).execute()
You would require a space name where you can post the code. You will get the same from hangout chat response.
It’s possible to do so using JavaScript, python, (possibly more). You can check out examples here: https://github.com/gsuitedevs/hangouts-chat-samples/tree/master/node/basic-cloud-functions-bot
If you’re using cards and JavaScript I would encourage you to checkout my library here: https://github.com/BaReinhard/hangouts-card-helper
I’m also in the process of creating another example for JavaScript that is more async focused that should provide and example that’s a bit easier to reason about the code. Will link when the PR is pushed.
Edit:
I realize that you mentioned REST api. The above answer is more useful for a specific bot that can be accessed #mentions. However, if you can provide us with a bit more information I can better fix my answer to answer your question.

OAuth2 with Satellizer and a generic OAuth2 provider

I'm having much trouble getting OAuth2 to work with a generic OAuth2 provider. Here's the situation.
A service provides an OAuth2 authentication method to where I want to authorize with. I've created an AngularJS app that has the following configuration for satellizer:
authProvider.baseUrl = 'http://localhost:3030/user/authorize';
$authProvider.oauth2({
name: 'customname',
url: '/token',
clientId: 'someapp',
requiredUrlParams: ['scope'],
scope: ['profile'],
authorizationEndpoint: 'http://location.to.oathserver',
redirectUri: 'http://localhost:3000'
});
The baseUrl points to my node server that should handle the middleware part.
I've also the following code that triggers the authentication part.
$scope.authenticate = function(provider) {
$auth.authenticate(provider)
.then(function(response) {
console.log(response);
})
.catch(function() {
//something went wrong
});
}
So far this all seems to work great and looks very similar to what is documented by Satellizer! Now once I start the angular app and start the authentication I see requests coming by that target my Node service.
Next I've my node.js service that hooks to the 'user/authorize/token' URL. Here's the code:
router.options('/authorize/token', function(req, res, next) {
//var token = req.header('Authorization').split(' ')[1];
res.end();
});
and:
router.post('/authorize/token', function(req, res, next) {
var authCode = req.param('code');
var cliendId = req.param('clientId');
var payload = jwt.decode(authCode, 'mySecret');
});
Here's where it all seems to go wrong. First I seem to get an OPTIONS request. I've not really an idea what to do with it as I can't seem to find anything in the documentation about an OPTIONS request. I thought it would might contain the 'Authorization' header but that doesn't seem the case so I close the connection with a res.end();
I also inspected the request in Chrome but I can't seem to find a header that has this exact name.
Next I get a POST request. This does seem to contain some things, hooray! I get the following object:
{
code: "ZFFeat9pWfHzw4rGmjFYwucPRMFnBOkd2odEObvo",
cliendId: "someapp",
redirectiUri: "http://localhost:3000"
}
This looks to me like the authorization code that I should have to decode. That's what you see me trying as well in the code above. Unfortunately this seems to throw me an error
Error: Not enough or too many segments
This tells me I'm doing probably something wrong, and I got stuck.
I do have some PHP code that seems to work for someone else but I don't fully understand and can't really relate the code to my code since PHP is not my speciality and node.js/JavaScript not his. So here goes the PHP code:
handle_cors(); // Handle CORS for cross domain requests
// Get JSON data
$input = json_decode(file_get_contents("php://input"), true);
// Create Provider
$provider = new SomeApp\OAuth2\Client\Provider\SomeApp([
'clientId' => 'someapp',
'clientSecret' => 'mySecret',
'redirectUri' => $input['redirectUri'],
]);
// Optional: Now you have a token you can look up a users profile data
try {
// Try to get an access token (using the authorization code grant)
$token = $provider->getAccessToken('authorization_code', [
'code' => $input['code']
]);
// We got an access token, let's now get the user's details
$user = $provider->getResourceOwner($token);
header('Content-Type: application/json');
$result = $user->toArray();
$result['token'] = create_token('my-example-key', $user->getId());
echo json_encode($result);
exit();
} catch (Exception $e) {
// Failed to get user details
exit('Oh dear...' . $e->getMessage());
}
Hopefully someone can help me out! Thanks in advance.
Sorry guys, I've been able to solve it myself. I found out that I was missing some URL's to POST to and GET from. After that the examples from Satellizer became clear and was able to use them almost as a carbon copy.

How to check CSRF token using AJAX and CakePHP 3 when user is not logged in?

So I made my site live and I am entering into the public realm where people aren't always nice. I just started learning about CSRF and saw that it was something I needed when I made my cakephp 3 site live. As seen here!
I added the csrf component and the security component to my site, but I have 1 major problem. Now, when users want to sign up they can't. I use a custom form for stripe to send payment, but also add a user using ajax to my database. The user gets added first and then the payment is processed and saves the order to the database as well.
According to stripe docs I add the token in a hidden value to the form after I click the submit button and can't help but notice that my new security is not allowing this to happen.
Since I am using ajax to send the post data to my users controller and adding a form input on submit,
How do I check the csrf token and make sure there isn't a security leak without disabling the security for the actions involved?
An example of how this is to be done would be greatly appreciated since examples seem to be lacking for doing this in cakephp 3. It is also hard for me to figure out how everything works since the cakephp 3 automagic adds the tokens to the forms and cookie. I am unsure how/where/what to check.
For pass X-CSRF-Token, use beforeSend parameter in your Ajax request, and define csrfToken value of cookie.
$.ajax({
url: '/foo/bar',
type: 'POST',
dataType: 'HTML',
data: data,
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},
})
.done(function(data) {
alert('done !');
});
According to stripe docs I add the token in a hidden value to the form after I click the submit button and can't help but notice that my new security is not allowing this to happen.
Cake's CSRF token would have no effect when POSTing to another site.
Since I am using ajax to send the post data to my users controller and adding a form input on submit,
How do I check the csrf token and make sure there isn't a security leak without disabling the security for the actions involved?
The CSRF token is available in cookie named csrfToken, so read that token in your javascript and set X-CSRF-Token header for your AJAX request. The CsrfCompoment will do the checking.
using js function:
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
...
then
$.ajax
({
type: "Post",
url: "URL_HERE",
data: {some_data},
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', getCookie('csrfToken'));
},
success: function (e) {
},
errors: function () {
}
});

How do I handle Token Authentication with AngularJS and Restangular?

I have an angular app that uses Restangular and ui.router.state.
This is what I am currently doing
I have an Endpoint /Token that accepts a username/pass and gives
back a bearer token and some user info.
On successful login I save off the userinfo and token into a global var, user.current and I also set Restangular's default headers to include the bearer token:
Restangular.setDefaultHeaders({Authorization: "Bearer " + data.access_token});
When a user wants to access a route that has requiredAuth = true (set in the routeprovider as custom data like Access routeProvider's route properties) I check the user.current to see if its set.
a. If user.current is set, take them to the route.
b. If user.current is null or if the token would be expired (based on time) send them to /login
Problems/Concerns
If I Ctrl+R I lose my user info and the user has to log in again.
a. Should I be saving off the bearer token or credentials into a cookie or something and have a user service try to grab that in the event that user.current == null?
Am I even approaching this right? Seems like something that literally 100% of people using AngularJS would want to do, yet, I can't find an example that aligns with my situation. Seems like Angular would have mechanisms built in to handle some of this auth routing business...
When do I need to be getting a new token/verifying the current one? Do I just let anyone with devtools set something like isAuthorized = true so they can get to /admin/importantThings but then let the calls to /api/important things fail because they don't have a valid bearer token or should I be verifying that they have a valid token before I even let them get to that route?
You could put it in localStorage (always kept) or sessionStorage (cleared when browser is closed). Cookies are technically also a possibility, but don't fit your use case that well (your back end checks a separate header and not a cookie)
I guess there are many ways to skin a cat.
Always depend on server-side checks. Client-side checks might offer some increased usability, but you can never depend on them. If you have a lot of buttons that result in going to a login screen, it will be faster if you keep the client-side check. If this is more the exception than the rule, you could instead redirect to the login page when you get a 401 Unauthorized when calling your back end.
Here is an example of how you can manage your token:
/* global angular */
'use strict';
(function() {
angular.module('app').factory('authToken', ['$window', function($window) {
var storage = $window.localStorage;
var cachedToken;
var userToken = 'userToken';
var authToken = {
setToken: function(token) {
cachedToken = token;
storage.setItem(userToken, token);
},
getToken: function() {
if (!cachedToken) {
cachedToken = storage.getItem(userToken);
}
return cachedToken;
},
isAuthenticated: function() {
return !!authToken.getToken();
},
removeToken: function() {
cachedToken = null;
storage.removeItem(userToken);
}
};
return authToken;
}]);
})();
As you can see I use "$window.localStorage" to store my token. Like "Peter Herroelen" said in hist post.

Accessing / Setting Angular Cookie to interact with ServiceStack

I am working in a Windows Auth environment, and have created a Cookie in Angular to hold the currently logged in user's fullname:
returnsApp.run(["$cookies", "UserService", function($cookies, userService) {
userService.getUser().then(function(user) {
$cookies["ss-id"] = user.data.result.fullName;
console.log($cookies["ss-id"]); // Outputs: BiffBaffBoff (correct!)
});
}]);
Then when I try and access this cookie on the Server, inside my Service (It's hosted on a different server if that helps?), the cookie is null:
Cookie cookie;
Request.Cookies.TryGetValue(SessionFeature.SessionId, out cookie);
if (cookie == null)
throw new ArgumentException("User not found!");
I think I am missing a step, perhaps passing this cookie value along in the header when I make the service call? FYI, here is how I am making the service call:
var createReturn = function (returnObj) {
return $http.post(url, returnObj);
};
Something similar happened to me, but the other way,setting up a cookie in the server and when I tried to read in the client it was always null, I think you need to configure SS to be able to create non HttpOnly cookies.
try to put this setting in your host configuration:
Config.AllowNonHttpOnlyCookies = true;
As far I know you wanted to access an OOB auth cookie, I'm not quite sure if that cookie is only available in the server side, if that's the case try to create another cookie with the information you want to share between the client in the server and set the HttpOnly = false, that worked for me and it's something like that:
var resp =service.RequestContext.Get<IHttpResponse>();
resp.Cookies.AddCookie(new Cookie { Name = "r", Path = "/", Value = "from server", HttpOnly = false, Discard = false, Expires = DateTime.Now.AddHours(12) });
I hope that helps

Resources