I am trying to make a WebAPI call from server script and I am getting an authentication error.
This is how my server.js file looks like:
var app = require('http').createServer()
, io = require('socket.io').listen(app)
, fs = require('fs')
, moment = require('moment')
, request = require('request'); //https://github.com/mikeal/request
app.listen(8000, function () {
console.log('server started');
doSomethingOnServerStart();
});
function doSomethingOnServerStart()
{
console.log('Getting something from server');
request.get({
url: 'http://localhost:63213/Api/MyAPI/GetSomething',
},
function (error, response, body) {
console.log(response.statusCode);
if (response.statusCode == 200) {
console.log('data received from server');
} else {
console.log('error: ' + response.statusCode);
console.log(body);
}
});
}
I would like to avoid storing hashed username/password in the server.js file as that file can be downloaded by anyone.
To address your question of storing the hashed username/password in the server.js file this is the solution I came up with. Create a file called local.config.js which is a module to set all of the process.env variables. Make sure that your .gitignore (or whatever your SCM equivalent to that is) will ignore all files with local.* (for example) so it doesn't get into your versioning either.
Then you'll want to make sure that you only load this when you're running locally. So on the server make an environment variable (or find one that's on there already) that only exists when you're not running locally. If that property of process.env.OPENSHIFT_APP_NAME (for example) doesn't exist, then you must be running local and in that case require the local.config.js and setup the environment variables from that.
Then on the server, set the environment variables. This is how you do it on OpenShift. You could make one that is: MY_USERNAME and another one that's MY_PASSWORD or something. Then you access those with process.env.MY_USERNAME or process.env.MY_PASSWORD.
This method works for me and I believe many people do this to protect API keys and secrets.
I just finished typing this and thinking about it I would recommend you make this a separate question. Let me know if you do this and I'll post this there instead so you can accept it if it's to your liking. You shouldn't ask two questions in one post :)