How to automatically refresh a token in 4.5

1979
1
12-11-2017 11:48 AM
AndrewLindley
New Contributor III

Im trying to refresh an ArcServer token in the JS API, but can't seem to figure it out.

This gist is: I want to refresh the server token every hour automatically without requiring more input from the user while within the same session (ie. the user hasn't closed the browser window).

Right now I get the token with a basic POST request to the server and then register that token with the ID manager like this:

IdentityManager.registerToken({
   server: "//exampleUrl/server/rest/services/",
   token: localStorage.getItem('token')
});‍‍‍‍

That's it and it works just fine, but when the token expires in an hour (which we want), I don't have a way to simply refresh the token. Since I'm not storing the password like I am the username, I can't simply fire the POST request again to generate a new token.

I've looked at creating a credential object which has a refreshToken() method, but can't get it to work, and to be honest I don't fully understand the credential class as it relates to the ID manager, serverInfos, and authentication in general. I tried replacing the above code to register the token with ID manager with the following code with no success:

var serverInfo = new ServerInfo();
serverInfo.server = "//exampleUrl/server1";
serverInfo.tokenServiceUrl = "exmapleUrl/rest/generateToken";

let idObject = {serverInfos: [serverInfo]};
let credential = {
   server: "exampleUrl/server1/",
   ssl: true,
   token: localStorage.getItem("token"),
   userId: localStorage.getItem("username")
}

idObject.credentials = [credential];
IdentityManager.initialize(idObject);‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

(used this as a guide, but I'm not sure Jeff Pace was using the 4.x API)

Does anyone have any examples of using the refreshToken() method, or any insight into the best way to accomplish an automatic token refresh within the API?

1 Reply
JadeFreeman
Occasional Contributor III

Here is some code I have used in the past to do something similar that might be a starting point.  I was using this class in several Web App Builder applications.  It did not automatically refresh a token like you are trying to do but intercepted presentation of the user sign in dialog triggered when the IdentifyManager detects a missing or invalid (expired) token.

0 Kudos