Overview

You will learn: how to create a new app with a login to display a layer that is not accessible to the public.

When you don't want to share content with everyone, the ArcGIS API for JavaScript and ArcGIS Online provide a robust security framework. We recommend developers utilize OAuth2 instead of handling user credentials when an app requires a login.

In this lab you will register your application in advance and tell us where you'd like us to redirect users. Later on, we verify that information when you ask them to sign in directly to arcgis.com.

NOTE: Unlike our other JavaScript labs, you won't be able to use CodePen. You'll have to run the code locally.

Steps

Pre-configure OAuth2 for your app

  1. Sign into ArcGIS for Developers.

  2. Dashboard + > New Application > Register New Application

    • Title: Access Private Layer App
    • Tags: OAuth
    • Description: Access Private Layer App
    • Click Register Application
  3. At the top, click Authentication and add the following redirect URI:

    • Redirect URI http://localhost/
  4. Make note of your Client ID as you'll need this in the next step.

Create your app

  1. Instead of using CodePen, create a file in your //localhost web directory and add the following code to create a basic starter app.


    <!DOCTYPE HTML>
    <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"
      />
      <title>ArcGIS DevLabs: Access traffic using OAuth2</title>
      <link rel="stylesheet" href="https://js.arcgis.com/4.8/esri/css/main.css">
      <script src="https://js.arcgis.com/4.8/"></script>
      <style>
        html,
        body, #viewDiv{
          font-family: Avenir Next W00;
          font-size: 14px;
          width: 100%;
          height: 100%;
          margin: 0px;
          padding: 0px;
        }
    
        .action {
          color: blue;
          cursor: pointer;
          text-decoration: underline;
        }
      </style>
    </head>
    <body>
      <div id="anonymousPanel" style="display: block; padding: 5px; text-align: center;">
        <span id="sign-in" class="action">Sign In</span> to see live traffic.
      </div>
    
      <div id="personalizedPanel" style="display: none; padding: 5px; text-align: center;">
        Welcome <span id="userId" style="font-weight: bold;"></span> &nbsp;-&nbsp;
        <span id="sign-out" class="action">Sign Out</span>
      </div>
      <!-- for the map -->
      <div id="viewDiv" style="display: none;"></div>
    </body>
    </html>
    

Add JavaScript to send users to arcgis.com to sign in.

In order to access secure content you need to launch the OAuth login and authenticate the user.

  1. In the file <head>, add a <script> tag and the JavaScript below. Be sure to substitue your Client_ID for the appId below.

    <script>
      require([
        "esri/portal/Portal",
        "esri/identity/OAuthInfo",
        "esri/identity/IdentityManager",
        "esri/Map",
        "esri/views/MapView",
        "esri/layers/MapImageLayer",
        "dojo/dom-style",
        "dojo/dom-attr",
        "dojo/on",
        "dojo/dom",
        "dojo/domReady!"
      ], function(
          Portal, OAuthInfo, esriId, Map, MapView, MapImageLayer,
          domStyle, domAttr, on, dom) {
    
        // ArcGIS Enterprise Portals are also supported
        var portalUrl = "https://www.arcgis.com/sharing";
    
        // subsitute your own client_id to identify who spawned the login and check for a matching redirect URI
        var info = new OAuthInfo({
          appId: "JTpyML5GgvA1jEoo", //*** Your CLIENT_ID goes here ***//
          popup: false // inline redirects don't require any additional app configuration
        });
        esriId.registerOAuthInfos([info]);
    
        // send users to arcgis.com to login
        on(dom.byId("sign-in"), "click", function() {
          esriId.getCredential(portalUrl);
        });
    
        // log out and reload
        on(dom.byId("sign-out"), "click", function() {
          esriId.destroyCredentials();
          window.location.reload();
        });
    
        // persist logins when the page is refreshed
        esriId.checkSignInStatus(portalUrl).then(
          function() {
            dom.byId('anonymousPanel').style.display = 'none';
            dom.byId('personalizedPanel').style.display = 'block'
    
            // display the map once the user is logged in
            // displayMap();
          }
        );
    
      }
    );
    </script>
    
  2. Run the http://localhost/privatelayer.html page and try to sign-in and sign-out.

Create a map and add a premium layer after login is complete.

After authenticated, if you have the correct permissions you can access private content or premium content hosted by Esri such as the Traffic Service.

  1. In the file, uncomment the displayMap() function and add the function below.

    // persist logins when the page is refreshed
    esriId.checkSignInStatus(portalUrl).then(
      function() {
        ...
        // display the map once the user is logged in
        //*** ADD ***//
        displayMap();
      }
    );
    
    //*** ADD ***//
    
    function displayMap() {
      var portal = new Portal();
    
      // Once the portal has loaded, the user is signed in
      portal.load().then(function() {
        dom.byId('viewDiv').style.display = 'flex';
    
        var map = new Map({
          basemap: "topo"
        });
    
        var view = new MapView({
          container: "viewDiv",
          map: map,
          zoom: 14,
          center: [-118.24,34.05]
        });
    
        var traffic = new MapImageLayer({
          url: 'https://traffic.arcgis.com/arcgis/rest/services/World/Traffic/MapServer'
        })
        map.add(traffic);
      });
    }
    
  2. Run the code. The map should display live traffic in Los Angeles after you sign in.

Congratulations, you're done!

Your app should look something like this.