Programmatically Log In to ArcGIS Online via Javascript Application

13027
13
01-07-2014 10:42 AM
BrianBeck
Regular Contributor
I have a Javascript Web Map Application using the Esri JS API that is accessing data in ArcGIS Online.  I don't want my users to have to log in to ArcGIS Online in order to access the content so I'd like the app to log in instead.

So far I was able to accomplish this using a proxy page that attaches a token to any requests for secured services.  This method works, but the proxy page creates a bottleneck and the performance decrease is very noticeable when using the app even when panning and zooming.

I've been looking at the documentation for the IdentityManager, IdentityManagerBase, and Credential classes in the JS API to see if there is a way to recreate the process used when the user is prompted for credentials by adding credentials to the Identity Manager programmatically.  So far I cannot figure out how to save a token in the IdentityManager for use by future requests.

Is there a way that I could use my proxy page to retrieve a token when the app is loaded and then add the token to the IdentityManager so it would automatically be added to any necessary requests and the user would not be prompted for credentials?
0 Kudos
13 Replies
JeffPace
MVP Alum

here is the code we use to do a hardcoded login

function initPredefinedSecurity() {

//alert('in initPredefinedSecurity');

                                serverInfo = new ServerInfo();

                                serverInfo.server = 'https://'+window.location.hostname+'/arcgis03';

                                serverInfo.tokenServiceUrl = 'https://'+window.location.hostname+'/arcgis03/tokens/generateToken';

                                serverInfo.shortLivedTokenValidity = 720;

                                esri.id.registerServers([serverInfo]);

                              

                             //add your own password

                                var def = esri.id.generateToken(serverInfo, {"username": "util", "password": ""});

                                def.addCallback(lang.hitch(this, function (tokenInfo) {

        //get token creation time in epoch

                                var creationTime = (new Date).getTime();

                                                //calculate the token expiration based on short lived token validity

                                var expirationTime = creationTime + (serverInfo.shortLivedTokenValidity * 60000);

                                                //create array of secured services

                                            

                                

                                var idObject ={};

                                idObject.serverInfos= [serverInfo];

                                var credentials={};

                                credentials.userId = "util";

                                credentials.server = "https://"+window.location.hostname+"/arcgis03";

                                credentials.token = tokenInfo.token;

                                credentials.expires = expirationTime;

                                credentials.ssl = false;

                                credentials.scope = "server";

                                credentials.validity = 720;

                                credentials.creationTime = creationTime;

                              

                              

                                idObject.credentials = [credentials];

                            

                              //credential object is correct

                                esri.id.initialize(idObject);

                              //  now create map

                                initMap();

                              

                                }));

                            };

CarlosNantes
Regular Contributor
// This works for apps created with web appbuilder. 
   function login(user, password){
      var serverInfo = esri.id.serverInfos[0]; 
      var userInfo = {};
      userInfo.username = user;
      userInfo.password = password;
      esri.id.generateToken(serverInfo, userInfo).then(function (response){
         response.server = serverInfo.server;
         response.userId = user;
         esri.id.registerToken(response);
      });
   }
0 Kudos
WarrenMedernach
Frequent Contributor

Hello Carlos

Can you provide some further details on where and how this was implemented?

Thanks so much,


Warren

0 Kudos
CarlosNantes
Regular Contributor

Hello, Warren.

We have a customized web appbuilder application that has protected widgets and protected maps.
That function helpped me to login on our portal for arcgis without the need of the default popup of authentication.

If the default popup works for you, you could just use something like this snippet:

require([
   'esri/arcgis/Portal'
], function(
   arcgisPortal
) {
var PORTAL_ARCGIS_URL = '';

function openAuthPopupIfUserNotSignedIn() {
   var portal = new arcgisPortal.Portal(PORTAL_ARCGIS_URL);
      portal.signIn().then(function(portalUser) {
      console.log(portalUser.credential);
      // portalUser.credential.token has what you need to make requests to protected resource,
      // if the user you provided has access to it.
    }, function(error) {
       console.err(error);
    });
}
openAuthPopupIfUserNotSignedIn();
});


To test either this snippet or the previous function you could access your web appbuilder app and put them on the browser debugger.
In both casses, after the authentication completes, the global object esri.id.credentials[0].token will have the token to use for subsequent requests to protected resources.