Skip To Content

Use OAuth 2.0 authentication

In this topic

You may have used OAuth 2.0 to log on to third-party applications using a social network account, such as Twitter or Facebook. For general information about OAuth 2.0 in ArcGIS and how to use it in different scenarios, see OAuth 2.0 authentication. You'll find complete samples using OAuth under the Online Services category in the ArcGIS Runtime SDK samples for .NET.

As a developer using the ArcGIS platform, you can use OAuth 2.0 to build the following two types of apps:

  • Apps that target users of the ArcGIS platform—These apps allow users to log in to the platform via your app. These types of logins are known as user logins. In this scenario, your app redirects to a page that prompts the user for their ArcGIS Online user name and password, and uses their credentials to access content.
  • Apps that target users who are unknown to the ArcGIS platform—These apps need to log in to the platform for the user. These types of logins are known as app logins. In this scenario, your app accesses content using hard-coded credentials that belong to the app. This allows access to content to which the user otherwise would not have permission.
Tip:

Authenticating with ArcGIS for Portal or an organization account for ArcGIS Online provides a way to license your ArcGIS Runtime SDK app at the Standard level. See the License your app topic for more details.

OAuth user logins

OAuth user logins allow app users to authorize themselves on an ArcGIS portal and access secured resources for which they have permission, without the app handling the user's credentials. User logins can be implemented in all types of apps: browser-based Web apps, server-based Web apps, device or tablet-based apps, and desktop apps. A Web app redirects the user to the login page on the remote server, while device, tablet, and desktop-based apps use client side browser controls to integrate this login experience into the app. Your app receives a unique alphanumeric string known as an authorization code in response to a successful login. An authorization code provides proof to the server that the user has authenticated successfully and allows access to resources for which the user has permission.

There are a few broad steps involved for implementing a user login with OAuth 2.0 in your ArcGIS Runtime app.

  1. Respond to attempts to access secured resources in your app. If credentials are available for the server that hosts the resource, they are included automatically, otherwise the user is challenged to authenticate.
  2. If needed, get an authorization code for the user by opening a browser window (or control) and directing the user to a portal URL where they can log in using their user name and password. The user's credentials are entered directly at the specified server endpoint, so your app does not handle the user's login information. Upon successfully logging in at the specified URL, your app receives an authorization code for the user.
  3. Use the authorization code to get a corresponding access token, which is used to return secured resources for which the user has permission. The identity manager handles this step for you, automatically obtaining and storing an access token once an authorization code is available. All requests for secured resources require the access token, which is automatically included when using the IdentityManager in your app.
Note:

Much of the work involved in these steps can be handled by ArcGIS Runtime and classes in the ArcGIS Runtime SDK for .NET Toolkit. You will not need to write code to implement the entire workflow.

Register servers with IdentityManager

The IdentityManager class abstracts some of the details of working with secured resources in your app, such as challenging the user for credentials when a secured resource is accessed, storing credentials when the user successfully authenticates, and automatically including credentials in requests for secured content when they are available.

Note:

IdentityManager is a singleton class, which means there is always exactly one instance. You cannot instantiate an IdentityManager object in your code using new, instead you must reference it using the IdentityManager.Current static property.

IdentityManager maintains a collection of servers for your app that require authentication for access to secured services. You can register a server with the identity manager with its URL and indicate what type of authorization should be used. For OAuth user or app logins, you need to provide additional information about the client app:

  • Client ID—An alphanumeric string that identifies the app on the server. See the Get a Client ID and Secret section in this topic for instructions on creating a client ID for your app with ArcGIS Online.
  • Redirect URI—An address to which a successful authentication response is sent. For a server app, this might be the URL of a web service that can accept the authorization response. You can use the special value of urn:ietf:wg:oauth:2.0:oob to deliver the response to a portal URL (/oauth2/approval). This value is typically used by applications that don't have a web server or a custom URI scheme where the code can be delivered. When received by your app, the response is read from the authentication success page.

The following example registers a server with the IdentityManager with an OAuth user login authentication type (TokenAuthenticationType.OAuthAuthorizationCode) and defines some required information about the client app (OAuthClientInfo).

// Register the portal to use OAuth authentication
var serverInfo = new ServerInfo
{
	ServerUri = "https://www.arcgis.com/sharing/rest",
	TokenAuthenticationType = TokenAuthenticationType.OAuthAuthorizationCode,
	OAuthClientInfo = new OAuthClientInfo { ClientId = "2HEtx9ujil5rac8K", RedirectUri = "urn:ietf:wg:oauth:2.0:oob"}
};

IdentityManager.Current.RegisterServer(serverInfo);

When a request is made for a secured resource, the identity manager can see if the request is to one of its registered servers. If the user has already authorized with the server, the identity manager automatically includes the user credential with the request. Otherwise, the identity manager challenges the user for login information according to the authorization method that's been defined for the registered server. The following code causes a challenge for the user to provide a login if the server is secured and registered with the identity manager.

var portal = await ArcGISPortal.CreateAsync(new Uri(SERVER_URI));

Caution:

If a server allows public access for unsecured resources, the user may be given access as an anonymous user rather than being challenged for authorization. To explicitly challenge the user, call IdentityManager.GetCredentialAsync().

Handle access to secured content

Challenging the user for a login is handled by a component assigned to the IdentityManager.ChallengeHandler property. For authentication with ArcGIS tokens, the challenge handler is responsible for displaying a UI from within the app that allows the user to provide a user name and password. For OAuth, the aim is to prevent the app from having to deal directly with login information, the user is directed to a login UI hosted by the server. To implement OAuth authorization, you must also define a handler for the IdentityManager.OAuthAuthorizeHandler property.

ChallengeHandler and OAuthAuthorizeHandler components can be created by implementing the IChallengeHandler and IOAuthAuthorizeHandler interfaces respectively. In most cases, the handlers provided by the ArcGIS Runtime SDK for .NET Toolkit are sufficient and save you from writing a lot of code. Follow the instructions in the Install the toolkit topic to add the toolkit to your project.

The following example assigns the ChallengeHandler and OAuthAuthorizeHandler properties for the identity manager using the components available in the toolkit (SignInChallengeHandler and OAuthAuthorizeHandler).

IdentityManager.Current.ChallengeHandler = new Esri.ArcGISRuntime.Toolkit.Security.SignInChallengeHandler 
                                                             { AllowSaveCredentials = true };
IdentityManager.Current.OAuthAuthorizeHandler = new Esri.ArcGISRuntime.Toolkit.Security.OAuthAuthorizeHandler();

The AllowSaveCredentials option for the SignInChallengeHandler gives the user the option to store their credentials so they can be used between sessions with your app.

Tip:

If you need to implement custom challenge or OAuth handlers, you can examine or borrow the code for the handlers in the ArcGIS Runtime SDK for .NET Toolkit. The solution and all the source code for the toolkit is available in the arcgis-toolkit-dotnet repository on GitHub.

With the handlers in place, the identity manager challenges requests for a secured resource on a registered server by redirecting the user to the login UI on the server. If the user authorizes successfully, an access token is returned and stored with the identity manager.

An access token is an alphanumeric string that provides a key for accessing the platform on behalf of the user, and must be sent with all requests for secured content on the server. The IdentityManager class manages access tokens for portals used by the app and automatically includes one when needed for requests made by ArcGIS Runtime classes.

Note:

When a user authenticates with a portal, in addition to the access token, the identity manager receives and stores a refresh token. The refresh token is used to obtain a new access token when it expires. The identity manager automatically handles getting the new access token using the refresh token when needed.

Sign in and out

The identity manager automatically handles authenticating for secured resources when they are accessed. You can also manually log the user on or off of a particular server if you need to. A server might offer both authenticated and anonymous access, for example, or you might want to let the user switch between logins to access different resources on the server.

To explicitly challenge the user to sign in, call IdentityManager.GetCredentialAsync as shown in the following example.

private async Task SignIn()
{
  	try
  	{
	   	var crd = await IdentityManager.Current.GetCredentialAsync
                                     (new CredentialRequestInfo { ServiceUri = PORTAL_URL }, true);
	   	IdentityManager.Current.AddCredential(crd);

     // access the portal as the authenticated user
  	 	this.portal = await ArcGISPortal.CreateAsync(new Uri(PORTAL_URL));
  	}
  	catch { } // can happen if user cancels the authentication
}

To sign out of a portal, you need to remove the credential stored with the identity manager. If the AllowSaveCredentials option is enabled for the challenge handler, you also need to clear credentails that may have been saved. The following example removes the credential for a particular server then reaccesses it with anonymous access.

private async Task SignOut()
{			
	  // clear the credential for the server from the IdenityManager (if it exists)
    foreach (var cred in IdentityManager.Current.Credentials)
    {
		     if (cred.ServiceUri.Contains(PORTAL_URL)) {
           IdentityManager.Current.RemoveCredential(cred);
       }
    }

    // clear the credentials cache from the SignInChallengeHandler so they won't be reused in the next session
    var signInHandler = IdentityManager.Current.ChallengeHandler 
                                     as Esri.ArcGISRuntime.Toolkit.Security.SignInChallengeHandler;
    signInHandler.ClearCredentialsCache();
    
	   // access the portal as anonymous
	   this.portal = await ArcGISPortal.CreateAsync(new Uri(PORTAL_URL));
}

App logins

If your app targets users unknown to the ArcGIS platform, the app can log in to the ArcGIS platform and access secured resources to which it has permission. Unlike the user logins described previously in this topic, your user will not be prompted with a UI to enter a login and password. Instead, your app is required to authenticate with the portal to receive an access token.

What does an app use to authenticate? The equivalent of user name and password for an app is Client ID and Client Secret. For an OAuth app login, your app needs to provide this information to the portal hosting the secured resources. As with a user login, your app receives an access token that the identity manager can use for working with secured resources.

Get a Client ID and Client Secret

Your app's Client ID and Client Secret are created by logging into your developer account at developers.arcgis.com. Click the Applications tab at the top of the page, and click New Application.

Provide a name, some tags (to make your app searchable), a description, and optionally a redirect URI. After creating the app, click the OAuth Credentials tab to see the Client ID and Client Secret generated for you.

Note:

The name you provide for your app on developers.arcgis.com does not need to match the name of your actual app. The information you provide when creating an app, such as the name, tags, description, and redirect URIs is essentially metadata and can be updated at any time. The Client ID and Client Secret are used by the server to uniquely identify your app and cannot be edited.

Client ID and Client Secret generated by developers.arcgis.com

The Client ID is required for user logins, as described previously, as well as for app logins. Unlike user logins, however, an app login also requires that you provide the Client Secret.

Caution:

With an app's Client ID and Client Secret, a user can access secured and billable content on ArcGIS.com. It's therefore important that you keep your app's Client Secret a secret. Care must be taken to prevent malicious users from extracting the client secret from the application using developer tools. For most apps, this implies that the app must have a server side component that keeps these credentials secure and performs work on behalf of the app.

Get OAuth client credentials

Getting credentials with an OAuth app login works much the same way as for user logins. The only differences are:

  • The ServerInfo.TokenAuthenticationType is set to TokenAuthenticationType.OAuthClientCredentials rather than TokenAuthenticationType.OAuthAuthorizationCode.
  • You must include the app's client secret by setting the OAuthClientInfo.ClientSecret property.

The following example gets an access token with an app login by registering the server with the identity manager and calling GetCredentialAsync. This will be seamless to the user and they will not be prompted for login information.

private async void OAuthAppLogin()
{
    // register the portal to use OAuth app authentication
    var serverInfo = new ServerInfo
    {
        ServerUri = PORTAL_URL,
        TokenAuthenticationType = TokenAuthenticationType.OAuthClientCredentials,
        OAuthClientInfo = new OAuthClientInfo
        {
            ClientId = CLIENT_ID,
            ClientSecret = CLIENT_SECRET,
            RedirectUri = REDIRECT_URI
        }
    };
    IdentityManager.Current.RegisterServer(serverInfo);

    // get a credential (app login, user will not be prompted)
    var credRequestInfo = new CredentialRequestInfo { ServiceUri = PORTAL_URL };
    var cred = await IdentityManager.Current.GetCredentialAsync(credRequestInfo, false);
}

There are some built-in limitations for using an OAuth App Login

  • Tokens obtained by applications can only read public content and services. Although you cannot use an App login with private content, if your goal is to distribute or sell an app to organizations without ArcGIS Online (no named users), you may control access to your content by using your own login mechanism (I.e. Identity) to the app.
  • Tokens obtained by applications may read premium content and services hosted by Esri and consume credits on behalf of the application organization.
  • Applications cannot create, update, share, modify, or delete items (layers, files, services, maps) in ArcGIS Online or Portal for ArcGIS.
  • Applications built using app login cannot be listed in the ArcGIS Marketplace.

Although it's possible to run code on the client that gets an app login using the Client ID and Client Secret, it's not recommended to do so if security is a concern. Remember that access to secured services by a malicious user may be billed to your app. This scenario is described in more detail in the topic App logins and OAuth 2.0 with some suggestions as to how to secure the Client Secret.

Related topics