Access ArcGIS Online items using OAuth 2.0

This sample shows you how to use inline web flow, as opposed to using a pop-up window that presents a login user interface. With inline web flow there is no popup window involved. It allows users to login to the ArcGIS platform using OAuth 2.0 functionality built directly into the IdentityManager.

This built-in functionality handles a lot of the fine-grained work that you would typically have to do when implementing this type of authentication.

The IdentityManager component simplifies the process of working with the token by appending it to requests and acquiring a new token when necessary. All you need to do is create an OAuthInfo object and specify the appId you received when registering your application. After this is set, pass this OAuthInfo object to the IdentityManager's registerOauthInfos method and the IdentityManager takes care of the rest.

There are four modules to focus on in this sample. These are:

"esri/portal/Portal",
"esri/identity/OAuthInfo",
"esri/identity/IdentityManager",
"esri/portal/PortalQueryParams"
  1. The first step is to create an OAuthInfo object and register it with the IdentityManager.
var info = new OAuthInfo({
  // Swap this ID out with registered application ID
  appId: "q244Lb8gDRgWQ8hM",
  // Uncomment the next line and update if using your own portal
  // portalUrl: "https://<host>:<port>/arcgis"
  // Uncomment the next line to prevent the user's signed in state from being shared with other apps on the same domain with the same authNamespace value.
  // authNamespace: "portal_oauth_inline",
  popup: false
});

esriId.registerOAuthInfos([info]);
  1. Next, check if the user is signed in.
esriId.checkSignInStatus(info.portalUrl + "/sharing").then(
  function() {
    displayItems();
  }
).otherwise(/*give user an option to sign in*/);
  1. Once signed in, retrieve the credentials.
esriId.getCredential(info.portalUrl + "/sharing");

Similarly, when a user signs out, destroy the credentials.

esriId.destroyCredentials();
  1. Once the user signs in, query the Portal for items.
var portal = new Portal();
// Setting authMode to immediate signs the user in once loaded
portal.authMode = "immediate";
// Once loaded, user is signed in
portal.load().then(function() {
  // Create query parameters for the portal search
  var queryParams = new PortalQueryParams({
    query: "owner:" + portal.user.username,
    sortField: "numViews",
    sortOrder: "desc",
    num: 20
  });

  // Query the items based on the queryParams created from portal above
  portal.queryItems(queryParams).then(createGallery);
});

Please see the authentication documentation for additional detailed information about user logins and OAuth 2.0. For another tutorial, please see the DevLabs - Access private layers exercise.

Sample search results

TitleSample

There were no match results from your search criteria.