PSIcapture Walkthrough: OAuth2 Authentication

version 7.8.0.0.0.35+

version 7.9.0.1.0.113+

 

Download Link Pending

 

 Audience

This article is intended for PSIcapture Administrators.

 

Overview

In the PSIcapture versions listed above, OAuth2 authentication was added to facilitate the latest security options available from Microsoft’s Azure Active Directory system.

NOTE: In order to configure OAuth2 for your unique environment, you must have administrator level permissions that allow access to the Azure AD Admin center, as well as permissions to create and modify registered applications.

 

You can use the OAuth authentication service provided by Azure Active Directory to enable your EWS Managed API applications to access Exchange Online in Office 365. To use OAuth with your application you will need to:

  1. Register your application with Azure Active Directory.
  2. Add code to get an authentication token to get an authentication token from a token server.
  3. Add an authentication token to EWS requests that you send.

NOTE: OAuth authentication for EWS is only available in Exchange Online as part of Microsoft 365. EWS applications that use OAuth must be registered with Azure Active Directory.

To use the code in this article, you will need to have access to the following:

There are two types of OAuth permissions that can be used to access EWS APIs in Exchange Online. Before you proceed with the tutorial, you will need to choose the specific permission type to use.

  • Delegated permissions are used by apps that have a signed-in user present. For these apps, either the user or an administrator consents to the permissions that the app requests and the app can act as the signed-in user when making API calls.
  • Application permissions are used by apps that run without a signed-in user present; for example, apps that run as background services or daemons and can access multiple mailboxes.

Configure OAuth2 Authentication (Microsoft Graph)

Use the following procedure to authenticate your PSIcapture Auto Import email connection using the new OAuth2 protocol.

OAuth2 authentication was added to facilitate the latest security options available from the Microsoft Azure Active Directory system.

Note: In order to configure OAuth2 for your unique environment, you must have administrator level permissions that allow access to the Azure AD Admin center, as well as permissions to create and modify registered applications.

To use OAuth with your application, complete the procedures below.

Register your application with Azure Active Directory

Delegated permissions are used by apps that have a signed-in user present. For these apps, either the user or an administrator consents to the permissions that the app requests and the app can act as the signed-in user when making API calls.

Application permissions are used by apps that run without a signed-in user present; for example, apps that run as background services or daemons and can access multiple mailboxes.

Register your Application

To use OAuth, an application must have an application ID issued by Azure Active Directory. In the following procedure, it is assumed that the application is a console application, so you need to register your application as a public client with Azure Active Directory. You can register an application in the Azure Active Directory admin center or by using Microsoft Graph.

    1. Open a browser and navigate to the Azure Active Directory admin center and log in using a personal account (aka: Microsoft Account) or Work or School Account.
    2. Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.
    3. Select New registration. On the Register an application page, set the values as follows.
    4. Set Name to a friendly name for your app.
    5. Set Supported account types to the choice that makes sense for your scenario.
    6. For Redirect URI, change the dropdown to Public client (mobile & desktop) and set the value to:
      https://login.microsoftonline.com/common/oauth2/nativeclient
    7. Select Register. On the next page, copy the values of the Application (client) ID and Directory (tenant) ID and save them, as you will need them later.

Configure for App-only Authentication (Microsoft Graph)

To grant permissions using Microsoft Graph, navigate to Microsoft Azure Active Directory>Home>App Registrations and left-click on the app created in the steps above.

Select API Permissions on the left-hand side.

Select Add a permissions and add the following:

  • IMAP.AccessAsUser.All
  • User.Read

This completes the Microsoft Graph permissions granting process.

Input Client and Tenant ID within PSIcapture Email Connector

To input the recorded Application (client) ID and Directory (tenant) ID navigate to PSIcapture>Capture Profile>Auto Import>Monitored Locations and left-click on the connection you wish to edit. If no connection exists, select Add, otherwise select Edit. Then, click on the Email radio button.

Input the Application (client) ID recorded in the steps above into the Client ID field.

After receiving confirmation, input the Directory (tenant) ID recorded in the steps above into the Tenant ID field and click Authorize.

Configure monitored folder settings as needed and click Save.

 

Alternatively, if required, a method using EWS can be employed, and is described below.

 

Configure for App-only Authentication (Manual EWS)

  1. To use application permissions, follow these additional steps for EWS manually.
  2. Select Manifest in the left-hand navigation under Manage.
  3. Locate the requiredResourceAccess property in the manifest, and add the following inside the square brackets ([]):
JSONCopy
{
"resourceAppId": "00000002-0000-0ff1-ce00-000000000000",
"resourceAccess": [
{
"id": "dc890d15-9560-4a4c-9b7f-a736ec74ec40",
"type": "Role"
}
]
}
  1. Select Save.
  2. Select API permissions under Manage. Confirm that the full_access_as_app permission is listed.
  3. Select Grant admin consent for org and accept the consent dialog.
  4. Select Certificates & Secrets in the left-hand navigation under Manage.
  5. Select New client secret, enter a short description and select Add.
  6. Copy the Value of the newly added client secret and save it, you will need it later.

 

Code Examples

 

Get a token with app-only auth

 

// Using Microsoft.Identity.Client 4.22.0
var cca = ConfidentialClientApplicationBuilder
   .Create(ConfigurationManager.AppSettings["appId"])
   .WithClientSecret(ConfigurationManager.AppSettings["clientSecret"])
   .WithTenantId(ConfigurationManager.AppSettings["tenantId"])
   .Build();

// The permission scope required for EWS access

var ewsScopes = new string[] { "https://outlook.office365.com/.default" };

//Make the token request
var authResult = await cca.AcquireTokenForClient(ewsScopes).ExecuteAsync();

 

Full App-Only Authentication

 

using Microsoft.Exchange.WebServices.Data;
using Microsoft.Identity.Client;
using System;
using System.Configuration;

namespace EwsOAuth
{
   class Program
   {
       static async System.Threading.Tasks.Task Main(string[] args)
       {
           // Using Microsoft.Identity.Client 4.22.0
           var cca = ConfidentialClientApplicationBuilder
               .Create(ConfigurationManager.AppSettings["appId"])
               .WithClientSecret(ConfigurationManager.AppSettings["clientSecret"])
               .WithTenantId(ConfigurationManager.AppSettings["tenantId"])
               .Build();

           var ewsScopes = new string[] { "https://outlook.office365.com/.default" };

           try
           {
               var authResult = await cca.AcquireTokenForClient(ewsScopes)
                   .ExecuteAsync();

               // Configure the ExchangeService with the access token
               var ewsClient = new ExchangeService();
               ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
               ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
               ewsClient.ImpersonatedUserId =
                   new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "meganb@contoso.onmicrosoft.com");

               //Include x-anchormailbox header
                ewsClient.HttpHeaders.Add("X-AnchorMailbox", "meganb@contoso.onmicrosoft.com");

               // Make an EWS call
               var folders = ewsClient.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(10));
               foreach(var folder in folders)
               {
                   Console.WriteLine($"Folder: {folder.DisplayName}");
               }
           }
           catch (MsalException ex)
           {
               Console.WriteLine($"Error acquiring access token: {ex}");
           }
           catch (Exception ex)
           {
               Console.WriteLine($"Error: {ex}");
            }

           if (System.Diagnostics.Debugger.IsAttached)
           {
               Console.WriteLine("Hit any key to exit...");
               Console.ReadKey();
           }
       }
   }
}
Was this article helpful?
1 out of 1 found this helpful

Comments

0 comments

Please sign in to leave a comment.