Thursday, March 14, 2019

Register an app with the Azure Active Directory v2.0 endpoint

In order to access Planner data like Plans and Buckets, we are using GraphServiceClient and Authentication is done through AAD App – here are some details:

 

Develop line-of-business apps for Azure Active Directory

Registering the application means that developers can use Azure AD to authenticate users and request access to user resources such as email, calendar, documents and office 365 application such as Team, Planner, Graph Api.

In AAD App Registrations, we have 2 types of "Application Type": 
  • Web app / Api 
  • Native 

Before continuing further, we must know the difference between Web app & Native App

  • Native applications are public clients in OAuth2 parlance. Those apps are meant to run on a device and aren't trusted to maintain a secret - hence, their entry in the directory does not have the corresponding property. Without a secret, there is no way to assert the identity of the app - hence such apps cannot gain app level permissions and the portal UX reflects that.
  • Conversely web apps are, again in OAuth2 parlance, confidential clients. They can get delegated tokens for their users, but they can also use client credentials to get tokens as themselves. Native apps can obtain tokens for the user via the OAuth2 authorization grant.
You can find a complete overview of all supported topologies at https://azure.microsoft.com/en-us/documentation/articles/active-directory-authentication-scenarios/. Each scenario description point to more implementation oriented guidance. 

source: https://stackoverflow.com/questions/33054393/what-is-the-exact-difference-between-native-app-and-web-app-in-azure-active-dire

Create Web app / API

  • Step 1: Create
  1. Login to portal.azure.com
  2. Go to Azure Active Directory > App registrations > New Application Registration
  3. In the Name field, give a descriptive name
  4. Choose Web app / API
  5. For Sign-on Url: If you are doing a POC, give a http://localhost:{port number}/
If you are planning to host the code on Azure Web App, give 
https://{youwebapp}.azurewebsites.net/
  1. Click on Create


  • Step 2: Configure
  1. Once the App is created, click on Settings
  2. Under Keys, we are going to set the "Client Secret",
  • Enter a Key Name (descriptive)
  • Enter an Expiration Value
  • On Save, the Client Secret will be generated, take a note of it as it gets hidden once you leave the screen.
  1. Under Required permissions, based on all available API, set all necessary permissions you need to, please note here that after settings up permissions, you/AAD Admin need to "Grant" them explicitly otherwise it will not work.
  • Step 3: Take Note
  1. Application ID – which is the Client ID
  2. Client Secret as per step 10
  3. Tenant ID => Azure Active Directory > Properties > Directory ID

Web app / API – Usage

  • In this POC – I am getting the Current User Request [me] using GraphServiceClient.
  1. Download the project (use Nuget Manager to download necessary references).
  2. In the GraphController, update ClientId, ClientSecret, TenantId as per above step 12-13-14
  3. Update the UriString as per above step 5
  4. Build and run the code
  5. The entry point is the Gettotken responsible for the Authentication  - Access the code using following your local IIS url http://localhost:12345/Graph/Gettoken
<![if !supportLists]>A.       <![endif]>Get Authorization Code (see the solution for complete code)
AuthenticationContext authContext = new AuthenticationContext(authorityURL, true);

Task<Uri> redirectUri = authContext.GetAuthorizationRequestUrlAsync(resource, clientId, new Uri(uriString), UserIdentifier.AnyUser, string.Empty);

redirectUri.Wait();

return Redirect(redirectUri.Result.AbsoluteUri);

Please note here that the AbsoluteUri has to match with the UriString otherwise it won't work – this is an extra layer of security added by Microsoft.
Once successful, it will redirect to the Gettoken method once more to get the access token.

<![if !supportLists]>B.      <![endif]>Use Authorization Code to request the Access Token (see the solution for complete code)
string code = Request.Params["code"];

ClientCredential clientCredentials = new ClientCredential(clientId, clientSecret);

Task<AuthenticationResult> request = authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(uriString), clientCredentials);

request.Wait();

Session["code"] = request.Result.AccessToken;
return RedirectToAction("Index");

Once successful, it will redirect to the Index method for further processing.

<![if !supportLists]>C.       <![endif]>Use Authorization Code to request the Access Token (see the solution for complete code)
public ActionResult Index(string authenticationCode)
{
string code = (string)Session["code"];
GraphServiceClient graphClient = GetGraphClient(code);

//Get User information [me]
Task<User> meRequest = graphClient.Me.Request().GetAsync();
meRequest.Wait();
           
User resultMeRequest = meRequest.Result;
Response.Write(resultMeRequest.AboutMe);

return View();
}
Voila 😊 !

Create Native app

  • Step 1: Create
  1. Login to portal.azure.com
  2. Go to Azure Active Directory > App registrations > New Application Registration
  3. In the Name field, give a descriptive name
  4. Choose Native
  5. For Sign-on Url: Here it doesn't matter – give http://localhost:12345
  6. Click on Create.

  • Step 2: Configure
  1. Once the App is created, click on Settings
  2. Please note that here there is no way to set a Key as a Client Secret – why ? the explanation is given on the difference between Native app & Web app
  3. Under Required permissions, based on all available API, set all necessary permissions you need to, please note here that after settings up permissions, you/AAD Admin need to "Grant" them explicitly otherwise it will not work.

  • Step 3: Take Note
  1. Application ID – which is the Client ID
  2. Tenant ID => Azure Active Directory > Properties > Directory ID

Native App – Usage

  • Here the code is straightforward:
  1. Get Access Token
public static string GetAccessToken()
        {
            string AppId = "";
            string TenantId = "";
            string GraphResourceUrl = "https://graph.microsoft.com";
            string AuthorityUrl = "https://login.microsoftonline.com/" + TenantId;
            string RedirectUri = "http://localhost:12345/";

            try
            {
                AuthenticationContext authContext = new AuthenticationContext(AuthorityUrl, true);
                AuthenticationResult authResult = authContext.AcquireTokenAsync(GraphResourceUrl, AppId, new Uri(RedirectUri), new PlatformParameters(PromptBehavior.Auto)).Result;
                return authResult.AccessToken;

            }
            catch (Exception ex)
            {
            }
            return null;
        }
  1. Get GraphServiceClient
public static GraphServiceClient GetGraphClient(string graphToken)
        {
            try
            {
                DelegateAuthenticationProvider authenticationProvider = new DelegateAuthenticationProvider(
                (requestMessage) =>
                {
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
                    return Task.FromResult(0);
                });
                return new GraphServiceClient(authenticationProvider);
            }
            catch (Exception ex)
            {
            }
            return null;
        }
Voila 😊 !

No comments:

Post a Comment