Bypass user login dialog and automatically signing a user account

21526
21
06-28-2013 10:58 AM
ScottGrace
New Contributor III
I need to automatically sign in a user without requiring them to enter the username and password for the ArcGIS online account. I have a user name and password that i want to be able to use everytime a user tries to view a web app that is only viewable to an organization. When it is only visible to the organization you are required to sign in, i want to bypass the process and automatically login a user. I know that i need to use the token feature but im unable to make that work... here is what i have:

<script type="text/javascript">
      dojo.require("utilities.App");
      dojo.require("templateConfig.commonConfig");
      
      
        dojo.require("dojo.parser");
        dojo.require("esri.IdentityManager");
        var cred = "esri_jsapi_id_manager_data";
        var shortLivedTokenValidity=60;
        function init() {

            var idBase = new esri.IdentityManagerBase();
            //esri.config.defaults.io.proxyUrl = "proxy.ashx";
            var serverInfo = {
                server: "http://myserver:port",
                tokenServiceUrl: "http://myserver/arcgis/tokens",
                currentVersion: 10.1
            };
            var def = idBase.generateToken(serverInfo, { username: "user1", password: "user1" });
            def.addCallback(function (tokenInfo) {
        var idBase = new esri.IdentityManagerBase();
        //Short lived token is valid for 60 mins by defult 
                idBase.tokenValidity =shortLivedTokenValidity=60;
                var serverInfo = {
                    server: "http://myserver:port",
                    tokenServiceUrl: "http://myserver/arcgis/tokens/",
                    currentVersion: 10.1
                };
                
                esri.id.registerServers([serverInfo]);
               //get token creation time in epoch
                var creationTime = (new Date).getTime();
        //calculate the token expiration based on short lived token validity
                var expirationTime = creationTime + (shortLivedTokenValidity * 60000);
        //create array of secured services 
                var securedServices = [];
                for (var services in this.configData.mapService) {
                    securedServices.push(this.configData.mapService[services]);
                }
                var idString = dojo.toJson({ serverInfos: [serverInfo],
                    credentials: [{
                        userId: user1,
                        server: "http://myserver:port",
                        token: tokenInfo.token,
                        expires: expirationTime,
                        ssl: false,
                        creationTime: creationTime,
                        resources: securedServices
                    }]
                });
                // store it client side
                if (_supports_local_storage()) {
                    // use local storage

                    window.localStorage.setItem(this._jsAPIIDManagerData, idString);
                } else {
                    // use a cookie
                    dojo.cookie(this._jsAPIIDManagerData, idString, { expires: 1 });
                }
                this._loadCredentials();
        
      });
      
               
        }
    
     function _supports_local_storage() {
            try {
                return "localStorage" in window && window["localStorage"] !== null;
            } catch (e) {
                return false;
            }
        }

        function _loadCredentials() {

            var idJson, idObject;
            if (this._supports_local_storage()) {
                // read from local storage
                idJson = window.localStorage.getItem(this._jsAPIIDManagerData);
            } else {
                // read from a cookie
                idJson = dojo.cookie(this._jsAPIIDManagerData);
            }
            if (idJson && idJson != "null" && idJson.length > 4) {
                idObject = dojo.fromJson(idJson);
                esri.id.initialize(idObject);
            }
        }
        
    
    dojo.addOnLoad(init);


      var i18n;
      dojo.ready(function(){

      
        i18n = dojo.i18n.getLocalization("esriTemplate","template");
        var  defaults = {
        //The ID for the map from ArcGIS.com
        webmap: "mywebmapid",
        //Modify this to point to your sharing service URL if you are using the portal
        sharingurl: null,//for example: "http://www.arcgis.com",
        //The id for the web mapping application item that contains configuration info - in most
        ////When editing you need to specify a proxyurl (see below) if the service is on a different domain
        //Specify a proxy url if you will be editing, using the elevation profile or have secure services or web maps that are not shared with everyone.
        proxyurl: "",
        //cases this will be null.
        appid: "",
        //set to true to display the title
        displaytitle: true,
        //Enter a title, if no title is specified, the webmap's title is used.
        title: "",
        //Enter a description for the application. This description will appear in the left pane
        //if no description is entered the webmap description will be used.
        description: "",
        //specify an owner for the app - used by the print option. The default value will be the web map's owner
        owner: '',
        //Specify a color theme for the app. Valid options are gray,blue,purple,green and orange
        theme: 'gray',
        //Optional tools - set to false to hide the tool
        //set to false to hide the zoom slider on the map
        displayslider: true,
        displaymeasure: true,
        displaybasemaps: true,
        displayoverviewmap: true,
        displayeditor: true,
        displaylegend: true,
        displaysearch: true,
        displaylayerlist: true,
        displaybookmarks: true,
        displaydetails: true,
        displaytimeslider: true,
        displayprint: true,
        
        displayelevation: false,
        //This option is used when the elevation chart is displayed to control what is displayed when users mouse over or touch the chart. When true, elevation gain/loss will be shown from the first location to the location under the cursor/finger.
        showelevationdifference: false,
        displayscalebar: true,
        displayshare: true,
        //Set to true to display the left panel on startup. The left panel can contain the legend, details and editor. Set to true to
        //hide left panel on initial startup. 2
        leftPanelVisibility: true,
        //If the webmap uses Bing Maps data, you will need to provide your Bing Maps Key
        bingmapskey: commonConfig.bingMapsKey,
        //specify a group in ArcGIS.com that contains the basemaps to display in the basemap gallery
        //example: title:'ArcGIS Online Basemaps' , owner:esri
        basemapgroup: {
          title: null,
          owner: null
        },
        //Enter the URL's to the geometry service, print task and geocode service. 
        helperServices: commonConfig.helperServices,
        //Set the label in the nls file for your browsers language
        printlayouts: [{
          layout: 'Letter ANSI A Landscape',
          label: i18n.tools.print.layouts.label1,
          format: 'PDF'
        }, {
          layout: 'Letter ANSI A Portrait',
          label: i18n.tools.print.layouts.label2,
          format: 'PDF'
        }, {
          layout: 'Letter ANSI A Landscape',
          label: i18n.tools.print.layouts.label3,
          format: 'PNG32'
        }, {
          layout: 'Letter ANSI A Portrait',
          label: i18n.tools.print.layouts.label4,
          format: 'PNG32'
        }],
        printlayout: false,
        printformat: "PNG32",
        //Specify the geocoder options. By default uses the geocoder widget with the default locators. If you specify a url value then that locator will be used.
        placefinder: {
          "url": "",
          "countryCode":"",
          "currentExtent":false,
          "placeholder": "",
          "singlelinefieldname":""
        },
        
        link1: {
          url: '',
          text: ''
        },
        link2: {
          url: '',
          text: ''
        },
        //specify the width of the panel that holds the editor, legend, details
        leftpanewidth: 228,
        //Restrict the map's extent to the initial extent of the web map. When true users
        //will not be able to pan/zoom outside the initial extent.
        constrainmapextent: false,
        //Provide an image and url for a logo that will be displayed as a clickable image
        //in the lower right corner of the map. If nothing is specified then the esri logo will appear.
        customlogo: {
          image: '',
          link: ''
        },
        //embed = true means the margins will be collapsed to just include the map no title or links
        embed: false
      };
        
        var app = new utilities.App(defaults);
        app.init().then(function(options){
            initMap(options);
        });

      });

    </script>







The could for the token generation was originally posted here:
http://forums.arcgis.com/threads/73298-Possible-to-hard-code-credentials?highlight=token

and the rest of the code you see is from the basic viewer
0 Kudos
21 Replies
IanKramer3
New Contributor III
Scott, check out this post. I think its what you are looking for. 

http://forums.arcgis.com/threads/90031-Bypass-Identity-Manager-with-ArcGIS.com-OAuth-token-object?hi...
0 Kudos
ScottGrace
New Contributor III
kramer_usc,

I was trying to implement what you outlined on your thread...but i am unable to accomplish it, could you possibly provide me a sample?
0 Kudos
ScottGrace
New Contributor III
Scott, check out this post. I think its what you are looking for. 

http://forums.arcgis.com/threads/90031-Bypass-Identity-Manager-with-ArcGIS.com-OAuth-token-object?hi...


kramer_usc,

I was trying to implement what you outlined on your thread...but i am unable to accomplish it, could you possibly provide me a sample?
0 Kudos
IanKramer3
New Contributor III
Hi Scott,
I posted the sample HTML/JS on the thread I sent you above.  You will need to add in your webmap id, ArcGIS.com userID, and the token that you generate.

Make sure that you create a Web Mapping Application on your ArcGIS.com Organization account first.  Then you need to get the APPID and APPSECRET that is assigned to that application.  From there, you will need to put those two things in the URL below.  Then just copy out the returned token string (just the token property) and put it into the code I posted on my thread.  Ultimately, you will want to write this REST request into some sort of web-based authentication, but this should get you started.

Ian

https://www.arcgis.com/sharing/oauth2/token?client_id=APPID&client_secret=APPSECRET&grant_type=clien...
0 Kudos
ScottGrace
New Contributor III
Hi Scott,
I posted the sample HTML/JS on the thread I sent you above.  You will need to add in your webmap id, ArcGIS.com userID, and the token that you generate.

Make sure that you create a Web Mapping Application on your ArcGIS.com Organization account first.  Then you need to get the APPID and APPSECRET that is assigned to that application.  From there, you will need to put those two things in the URL below.  Then just copy out the returned token string (just the token property) and put it into the code I posted on my thread.  Ultimately, you will want to write this REST request into some sort of web-based authentication, but this should get you started.

Ian

https://www.arcgis.com/sharing/oauth2/token?client_id=APPID&client_secret=APPSECRET&grant_type=clien...



when i plug in my information and the rest request:
ready(function () {




parser.parse();
var webmapId = "****";
var userId = "*****";
var tokenStr = "<INSERT TOKEN HERE>";
var expireStr = "<INSERT TOKEN HERE>";

esri.request({
    url: "https://www.arcgis.com/sharing/oauth2/token?",
    content: {
       client_id : "*****",
       client_secret : "******",
       grant_type : "client_credentials"
    },
    handleAs: "json",
    load: tokenObtained,
    error: tokenRequestFailed
  });

function tokenObtained(response)
{
    tokenStr = response.access_token;
    expireStr = response.expires_in;
}
function tokenRequestFailed(response)
{

  console.log("in TORF", response);
}

var token = {
"server": "http://www.arcgis.com/sharing/rest",
"userId": userId,
"token": tokenStr,
"ssl": false,
"expires": expireStr
};

kernel.id.registerToken(token);

i get this error message on the logon window that says "The username and password are valid, but you don't have access to this resource." what am i doing wrong?


for the record when i log in with my arcgisonline credentials i am able to go through.
0 Kudos
IanKramer3
New Contributor III
What happens if you execute that OAuth2 token URL directly in a browser window?  Do you get back the JSON correctly with the token?
0 Kudos
ScottGrace
New Contributor III
What happens if you execute that OAuth2 token URL directly in a browser window?  Do you get back the JSON correctly with the token?


yes i do, i get

{"access_token":"blah blah..","expires_in":7200}

with URL
https://www.arcgis.com/sharing/oauth2/token?client_id=*****&client_secret=****&grant_type=client_cre...
0 Kudos
IanKramer3
New Contributor III
ok, let's eliminate your esri.request code block for right now and just try copying and pasting the token into the following part of the code as a string.  do the same for your userId as well.  The expires property is a integer and not a string.

var token = {
"server": "http://www.arcgis.com/sharing/rest",
"userId": "USERID",
"token": "TOKEN",
"ssl": false,
"expires": 7200
};
0 Kudos
IanKramer3
New Contributor III
Also, how did you set up the application on ArcGIS.com.  Did you create it as a "web application" or did you choose mobile, desktop, or application?  I set mine up as a Web Application with the "Ready to use" option and the API set to "Javascript".
0 Kudos