JSAPI: generating a security token from on-premise token server in code

3623
1
12-26-2014 10:30 AM
DirkVandervoort
Occasional Contributor II

I'm struggling to generate a security token from my on-premise token server. The SDK's documentation is not obvious.

My code is:

        var si = new esri.ServerInfo();

        si.tokenServiceUrl = "http://www.MyTokenDispenser.com/ArcGIS/tokens/";

        var imb = new esri.IdentityManagerBase();

        imb.on("credential-create", createdCredential);

        imb.generateToken({

          serverInfo:si,

          userInfo:{userName:"MyUserName", password:"MyPassword"}

         });

I want to catch the token in the createdCredential method.

This code throws an error in the JSAPI API:

TypeError: r is undefined

http://js.arcgis.com/3.12/

Line 663

We do not want to use the out-of-the-box login that comes with esri.IdentityManager, instead we want to generate our own tokens and credentials. I can use query GET to get a token and I can use esri.request to get a token so long as I enable a proxy, but the code is a bit messy and defeats the purpose of the ArcGIS JSAPI.

TIA for any guidance you can offer.

Tags (1)
0 Kudos
1 Reply
HeikoHeijenga
Esri Contributor

Use something like this:

require([
    "esri/IdentityManager",
    "esri/ServerInfo",
    "esri/Credential",
    "esri/request"
], function(
    idManager,
    ServerInfo,
    Credential,
    esriRequest
) {


    var serverInfo = new ServerInfo();
    serverInfo.server = "http://geocode.arcgis.com";
    serverInfo.tokenServiceUrl = "https://www.arcgis.com/sharing/generateToken";


    idManager.registerServers([serverInfo]);


    var userId = "MyUserID",
        password = "MyPassword";


    idManager.generateToken(serverInfo, {
        username: userId,
        password: password
    }).then(function(response) {
        idManager.registerToken({
            server: serverInfo.server,
            userId: userId,
            token: response.token,
            expires: response.expires,
            ssl: response.ssl
        });


        esriRequest({
            url: "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/geocodeAddresses",
            content: {
                f: "json",
                addresses: JSON.stringify({
                    records: [{
                        attributes: {
                            Address: "380 New York St",
                            City: "Redlands"
                        }
                    }]
                })
            }
        }).then(function(response) {
            console.log(response);
        });
    });
});
0 Kudos