That should work. That's the same logic as I suggested.Here is a simple code running on nodejs to generate token. 1. you don't have to generate a new token every time when a user opens the web app. You can share the common one as long as it's still not expired.2. On client side, you need to call setInterval(function(){'gettokenfunction'}, 2 hours);
var ex = require("express");
var app = ex();
var http = require("http"),
qs = require("querystring");
var userToken, userTokenExpire;
var getToken = function(userInfo, res){
var currentTime = new Date().getTime();
if (userToken && (userTokenExpire && userTokenExpire - 7200000 > currentTime) ) {
//-7200000 (it's 2 hours) ensures the token is valid for at least next 2 hours.
//any new request within the 2 hours will create a new token.
res.send({token: userToken, expires: userTokenExpire});
}
else {
var options = {
method: "POST",
host: /*ip address here*/,
path: "http://arcgisserverdomain/arcgis/admin/generateToken",
headers: {"Connection": "keep-alive", "host": /*ip address*/, "Content-Type": "application/x-www-form-urlencoded"}
};
var postData = qs.stringify({
username: userInfo.username,
password: userInfo.password,
client: "referer",
referer: "http://yourwebsitedomain/",
f: "json",
expiration:1440 //it can be up to 24 hours, which is 24*60 minutes
});
var request = http.request(options, function(response){
response.setEncoding('utf8');
response.on('data', function (chunk) {
userToken = JSON.parse(chunk).token;
console.log(userToken);
userTokenExpire = JSON.parse(chunk).expires;
console.log(userTokenExpire);
res.send(chunk);
});
});
request.write(postData);
request.end();
}
};
app.get("/gettoken", function(req, res){
var userInfo = {};
//userInfo.username = req.query.username;
//userInfo.password = req.query.password;
//if (!userInfo.username && !userInfo.password) {
//since you don't need user to provide username and password, hard-code it.
userInfo.password = username;
userInfo.username = password;
//}
getToken(userInfo, res);
});
app.listen(3000);