Overview

You will learn: how to use named user login credentials to access the ArcGIS Traffic Layer service.

The ArcGIS Platform supports several security methodologies that you can implement to access ArcGIS premium services and secure content. To implement OAuth 2.0, you can use your ArcGIS account to register an application and get a client id, and then configure your app to redirect users to login with their credentials when the service or content is accessed. This is known as the "named user login" authentication pattern. If the app uses premium services that consume credits, the user's account will be charged, not your account. Alternatively, you can use your own account to set up service proxies that allow your applications to access premium services without asking the user to authenticate themselves. In this case, your account is providing authentication and will be charged credits if credit-consuming services are used. This is known as the "app login" authentication pattern. To learn more about service proxies, see the Set up authenticated services lab.

In this lab you will implement OAuth 2.0 to redirect users to sign into ArcGIS so they can access the ArcGIS Traffic Layer service.

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 OAuth 2.0 for your app

  1. Sign into ArcGIS for Developers.

  2. Dashboard + > New Application > Register New Application

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

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

Create your app's HTML

  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.9/esri/css/main.css">
      <script src="https://js.arcgis.com/4.9/"></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 for users to authenticate themselves, you need to launch the OAuth login dialog. Execute the dialog when the "Sign in" button is clicked.

  1. In the file <head>, add a <script> tag and the JavaScript below. Specify the portalUrl and the appId for the OAuthInfo. Be sure to substitute your Client ID for the appId.

    <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 value 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 the Traffic Service layer after login is complete

The ArcGIS Traffic service is a premium service that can be used to visualize real time traffic speeds and incidents such as accidents, construction sites, or street closures. The service is free, but it does require applications to provide authentication to access it. The layer must be loaded after a user has been successfully authenticated.

  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.

Challenge

Use a service proxy to access the traffic serivce

If you would like to use the "App login" authentication pattern to access the ArcGIS Traffic service directly and prevent the application from prompting the user to sign in, you can use a proxy service.

  1. Go to the Set up authenticated services lab and create a proxy to access the ArcGIS Traffic Layer Service.

    NOTE: To set up the proxy you can use the application created in the first step or you can create a new application for all service proxies.

  2. In the dashboard, copy the Traffic Layer proxy URL and update the application code.

     var traffic = new MapImageLayer({
       //*** ADD ***//
       url: "https://utility.arcgis.com/usrsvcs/appservices/<your-id>/rest/services/World/Traffic/MapServer"
     });
    
  3. In your app, comment out all of the OAuth code and call the displayMap function when the application loads.

  4. Run the application again and it shouldn't prompt the user to sign in.