0% found this document useful (0 votes)
30 views41 pages

Handling Security Token Issues in Azure AD

Uploaded by

jas brar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views41 pages

Handling Security Token Issues in Azure AD

Uploaded by

jas brar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Deccansoft Software Services – Microsoft Azure Azure Active Directory

Agenda: Authentication and Authorization using Azure Active Directory


 Brief about Azure AD
 Application Types Scenarios
 Multi-Tenant vs Single-Tenant
 Application and Service Principal
 Programming using Active Directory Authentication Library (ADAL)
 Abount Microsoft Identity Platform
 About Microsoft Authentication Library (MSAL)
 Authentication flows
 Programming Authentication using [Link]
 Microsoft Graph API
 Integrating [Link] MVC Applications with Azure AD
 Integrating [Link] Web API Applications with Azure AD
 Claims Based Authentication
 Role Based Authentication
 Implementing Azure AD B2C Collaboration
 Social Identity Provider Authentication

Azure Active Directory


Microsoft Azure Active Directory (Azure AD) is Microsoft’s cloud-based identity and access management service.
Azure AD creates and manages credentials that help enterprise users sign in and access both internal and external
resources that are offered by your company or third-party companies more securely.
Azure AD's geographically distributed architecture combines extensive monitoring, automated rerouting, failover,
and recovery capabilities, which deliver company-wide availability and performance to customers.

1
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

You can use Azure AD to:


 Provide an identity management solution.
 Manage users and groups.
 Role based Access Control (RBAC).
 Enable federation between organizations.
 Identify irregular sign-in activity.
 Configure SSO to cloud-based SaaS applications like Office365, [Link], DropBox etc…
 Configure access to the on-premise applications.
 Configure multi-factor authentication (MFA).
 Extend existing on-premises Active Directory implementations to Azure AD.

Application Types Scenarios


These are the five primary application scenarios supported by Azure AD:
1. Web browser to web application: A user needs to sign in to a web application that is secured by Azure AD.
2. Single-page application (SPA): A user needs to sign in to a single-page application that is secured by Azure AD.
3. Web application to web API: A web application needs to get resources from a web API secured by Azure AD.
4. Native application to web API: A native application that runs on a phone, tablet, or PC needs to authenticate a
user to get resources from a web API that is secured by Azure AD.
5. Daemon or server application to web API: A daemon application or a server application with no web user
interface needs to get resources from a web API secured by Azure AD.

2
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

Single-tenant vs multi-tenant apps


There are two categories of applications that can be developed and integrated with Azure AD:
 Single tenant application - A single tenant application is intended for use in one organization. These are
typically line-of-business (LoB) applications written by an enterprise developer. A single tenant application
only needs to be accessed by users in one directory, and as a result, it only needs to be provisioned in one
directory. These applications are typically registered by a developer in the organization.
EndPoint:
 [Link]
 [Link]

 Multi-tenant application - A multi-tenant application is intended for use in many organizations, not just one
organization. These are typically software-as-a-service (SaaS) applications written by an independent software
vendor (ISV). Multi-tenant applications need to be provisioned in each directory where they will be used,
which requires user or administrator consent to register them. This consent process starts when an
application has been registered in the directory and is given access to the Graph API or perhaps another web
API. When a user or administrator from a different organization signs up to use the application, they are
presented with a dialog that displays the permissions the application requires. The user or administrator can
then consent to the application, which gives the application access to the stated data, and finally registers the
application in their directory.
 EndPoint: [Link]

About Azure AD Application and Service Principal

3
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

When you register an Azure AD application in the Azure portal, two objects are created in your Azure AD tenant:
1. An application object
2. A service principal object

Azure AD application is defined by its one and only application object, which resides in the Azure AD tenant where
the application was registered, known as the application's “home” tenant.
To access resources that are secured by an Azure AD tenant, the entity that requires access must be represented
by a security principal. This is true for both users (user principal) and applications (service principal). The security
principal defines the access policy and permissions for the user or application in the Azure AD tenant. This enables
core features such as authentication of the user or application during sign-in and authorization during resource
access.
Consider the application object as the global representation of your application for use across all tenants, and the
service principal as the local representation for use in a specific tenant. An application object therefore has a 1:1
relationship with the software application, and a 1:many relationships with its corresponding service principal
object(s).

Actors involved in OAuth 2:


1) User / Resource Owner: The resource owner is the end user who is giving access to some portion of his/her
account.
2) Authorization Server: The server where the client application is registered and returns the access token after
it gets consent from the resource owner for accessing protected resources hosted by a resource server.
3) Resource Server: The Web API or Web Service server which hosts the secured users protected resources and
are protected by OAuth2. The resource server validates the access-token and serves the protected resources.
Eg: Photo Sharing site, online bank service or any other service where users private stuff is kept.
4) Third party Client Application: The application that is attempting to get access to the user's account or a
resource form Resource Server. It can be website, desktop or mobile application or a set-top box or anything
connected to the web. Eg: Photo Printing Application/Website.

4
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

Azure AD Application Registration


 The application registration might include, depending on the type:
o Application ID URI: The identifier for an application. This value is sent to Azure AD during
authentication to indicate which application the caller wants a token for.
o Reply URL and redirect URI : For a web API or web application, the Reply URL is the location where
Azure AD will send the authentication response, including a token if authentication was successful.
For a native application, the Redirect URI is a unique identifier to which Azure AD will redirect the
user-agent in an OAuth 2.0 request.
o Application ID: The ID for an application, which is generated by Azure AD when the application is
registered. When requesting an authorization code or token, the Application ID and Key are sent to
Azure AD during authentication.
o Key/Secret: The key that’s sent along with an Application ID when authenticating to Azure AD to call
a web API

Active Directory Authentication Library (ADAL)

5
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

For clients that need to access protected resources, Azure AD provides the Active Directory Authentication Library
(ADAL). ADAL v1.0 enables application developers to authenticate users to cloud or on-premises Active Directory
(AD) and obtain tokens for securing API calls.
ADAL makes authentication easier for developers through features such as:
• Configurable token cache that stores access tokens and refresh tokens.
• Automatic token refresh when an access token expires, and a refresh token is available.
• Support for asynchronous method calls.
Available in multiple languages such as:
• C#
• JavaScript
• Objective C
• Java
• Python

Acquiring an Azure AD token by using ADAL:


using [Link];
using System;

class Program
{
static string appId = "457ffee2-d5f2-46a9-a26a-fd146b9952e6";
static string secret = "ZRFmm_57E.g_64CTxd.XO921l.59x52rSn";
static string tenantId = "82d8af3b-d3f9-465c-b724-0fb186cc28c7";
static void Main(string[] args)
{
var context = new AuthenticationContext("[Link] + tenantId);
var credential = new ClientCredential(clientId: appId, clientSecret: secret);
AuthenticationResult result = [Link](appId, credential).Result;
if (result == null)
throw new InvalidOperationException("Failed to obtain the JWT token");
var token = [Link];
}

6
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

Limitation of ADAL:
Can authenticate against only work and school accounts provisioned in Azure AD. Will not work with individual
Microsoft Account.

About Microsoft Identity Platform v2.0


Microsoft identity platform is an evolution of the Azure Active Directory (Azure AD) developer platform.
It allows developers to build applications that sign in all Microsoft Identities and get tokens to call Microsoft APIs,
such as Microsoft Graph, or APIs that developers have built.

The Microsoft identity platform consists of:


 OAuth 2.0 and OpenID Connect standard-compliant authentication service that enables developers to
authenticate any Microsoft identity, including:
o Work or school accounts (provisioned through Azure AD)
o Personal Microsoft accounts (such as Skype, Xbox, and [Link])
o Social or local accounts (via Azure AD B2C)
 Open-source libraries: Microsoft Authentication Libraries (MSAL) and support for other standards-compliant
libraries.
 Application management portal: A registration and configuration experience built in the Azure portal, along
with all your other Azure management capabilities.

7
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

Microsoft Authentication Library (MSAL):


 The library to streamline working with Microsoft identity platform from code:
o Obtains and manages tokens.
o Caches tokens by using a configurable cache.
o Refreshes tokens automatically when they expire.
o Supports asynchronous invocation.
 Available on multiple platforms such as:
o .NET
o JavaScript
o Android
o iOS
o Java

Public client and confidential client applications


Microsoft Authentication Library (MSAL) defines two types of clients:

8
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

1. Confidential client applications are apps that run on servers (Web Apps, Web API apps, or even
service/daemon apps). A web app is the most common confidential client. The client ID is exposed through the
web browser, but the secret is passed only in the back channel and never directly exposed.

Uses the MSAL ConfidentialClientApplication class.


string redirectUri = "[Link]
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithAuthority([Link], _tenantId)
.WithClientSecret(clientSecret)
.WithRedirectUri(redirectUri)
.Build();

2. Public client applications are apps that run on devices or desktop computers or in a web browser SPA. They're
not trusted to safely keep application secrets, so they only access Web APIs on behalf of the user. (They
support only public client flows.) Public clients can't hold configuration-time secrets, so they don't have client
secrets. Uses the MSAL PublicClientApplication class.

9
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

var app = PublicClientApplicationBuilder


.Create(_clientId)
.WithAuthority([Link], _tenantId)
.WithRedirectUri("[Link]
.Build();

Authentication flows:
 Authorization code: Native and web apps securely obtain tokens in the name of the user.
 Interactive: User authenticates by using a web browser. Mobile and desktops applications call Microsoft
Graph in the name of a user.
 Client credentials: Service applications run without user interaction.
 On-behalf-of: Application authenticates on behalf of a user.
 Implicit: Used in browser-based applications.
 Device code: Enables sign-in to a device by using another device that has a browser.
 Integrated Windows: Windows computers silently acquire an access token when they are domain joined.
 Username/password: The application signs in a user by using their username and password.
string[] scopes = { "[Link]" };
AuthenticationResult result = await [Link](scopes).ExecuteAsync();

Very Important: [Link]

Integrating Web Applications with Azure Active Directory (Record this)


10
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

Organizations that develop their own line-of-business (LOB) applications can protect access to those applications
by using Azure AD. Developers can enable their own custom applications to use Azure AD, and obtain the same
features that are available in the Azure AD gallery applications.

Web App Sign In & Sign Out with Azure AD:


In [Link] web apps, you can accomplish this using Microsoft's implementation of the community-driven OWIN
middleware included in .NET Framework 4.5.

Registering an AD App using Azure Portal


1. Azure Portal  Azure Active Directory  App registrations  + New registration

11
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

2. Provide Name="MySecuredWebApp", Redirect URI (optional) Select a platform = Web, Sign-on URL:
[Link] (Run the web application and replace the 44336 port with what ever is
assigned for your application)
3. Azure Portal  Azure Active Directory  App registrations  Select DssDemoApp  Settings  Properties
4. Copy Application ID

1. Create a New [Link] MVC Web Application


a) File  New  Project  [Link] Web Application  Name=DssDemoWebApp  OK
b) Select a template = MVC, Click on Authentication=None
c) Select Work and School Accounts
d) Cloud – Single Organization
e) Domain = <Copy value from DOMAINS tab in Active Directory of Azure Portal>
f) OK
2. Add the following to [Link] (6.0)
[Link]([Link])
.AddMicrosoftIdentityWebApp([Link]("AzureAd"));
[Link](options =>
{
//var policy = new AuthorizationPolicyBuilder()
// .RequireAuthenticatedUser()
// .Build();
//[Link](new AuthorizeFilter(policy));
});
And
[Link]();
[Link]();

2. Add the below to [Link]


{
"AzureAd": {
"Instance": "[Link]
"Domain": "[Link]",

12
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

"TenantId": "82d8af3b-d3f9-465c-b724-0fb186cc28c7",
"ClientId": "da1ebcac-01ec-4053-8078-93b057545eb6",
"CallbackPath": "/signin-oidc"
}
}

3. Remove the attribute [Authorize] from HomeController in Controllers\[Link]


4. Open the Controllers\[Link] file. You can access the user's claims in your controllers via the
[Link] security principal object.
[Authorize]
public IActionResult About()
{
[Link] = [Link](claim => [Link] == "name")?.Value;
[Link] = [Link](claim => [Link] ==
"[Link]
return View();
}

5. Edit Views/Home/[Link]
<link href="@[Link]("~/Content/[Link]")" rel="stylesheet" type="text/css" />
<h3>Main Claims:</h3>
<table class="table table-striped table-bordered table-hover">
<tr><td>Username</td><td>@[Link]</td></tr>
<tr><td>TenantId</td><td>@[Link]</td></tr>
</table>
<br />
<h3>All Claims:</h3>
<table class="table table-striped table-bordered table-hover table-condensed">
@foreach (var claim in (([Link]) [Link]).Claims)
{
<tr><td>@[Link]</td><td>@[Link]</td></tr>
}
13
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

</table>
<br />
<br />
@[Link]("Sign out", "SignOut", "Home", null, new { @class = "btn btn-primary" })

6. Finally, build and run your app.


If you haven't already, now is the time to create a new user in your tenant with a *.[Link] domain.
Sign in with that user, and notice how the user's identity is reflected in the top navigation bar. Sign out, and
sign back in as another user in your tenant. If you're feeling particularly ambitious, register and run another
instance of this application (with its own clientId), and watch see single-sign on in action.

Configure sign-in options – Multitenant vs Singletenant


Single Tenant Option:
If you want your application to accept sign-ins only from accounts that belong to a specific Azure AD instance
(including guest accounts of that instance)
Tenant parameter in [Link] should be as below
{
"AzureAd": {
"Instance": "[Link]
"Domain": "[Link]",
"TenantId": "82d8af3b-d3f9-465c-b724-0fb186cc28c7",
"ClientId": "da1ebcac-01ec-4053-8078-93b057545eb6",
"CallbackPath": "/signin-oidc"
}
}

Multi Tenant Option: Configure your application to allow sign-ins of work and school accounts from any
company or organization (multi-tenant)
1. Go back to Microsoft Azure portal - App registrations and locate the application you registered.
2. Select Authentication  select Supported account types = Accounts in any organizational directory.
3. Select Save.
4. Edit [Link]

14
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

"AzureAd": {
"Instance": "[Link] ",
"ClientId": "29d2c719-e33d-4ca4-a2eb-cd21459e701b",
"TenantId": "common",
"CallbackPath": "/signin-oidc"
}

Optional: To restrict access to only users of few tenants


5. Edit [Link] and add Main method
6. Add the following methods to [Link] (6.0)
private string ValidateSpecificIssuers(string issuer, SecurityToken securityToken,
TokenValidationParameters validationParameters)
{
var validIssuers = GetAcceptedTenantIds()
.Select(tid => $"[Link]
if ([Link](issuer))
return issuer;
throw new SecurityTokenInvalidIssuerException("The sign-in user's account does not belong to one of the
tenants that this Web App accepts users from.");
}
private string[] GetAcceptedTenantIds()
{
return new[]
{
"82d8af3b-d3f9-465c-b724-0fb186cc28c7",
"2de8d54d-5576-4bf6-b419-6065cb1e700e"
};
}

7. Edit Main method and add the below service configuration


[Link]<OpenIdConnectOptions>([Link], options =>
{
15
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

[Link] = new TokenValidationParameters


{
IssuerValidator = ValidateSpecificIssuers,
ValidateIssuer = true
};
});

To allow only Authorized Users to Login to the Application


5. Azure Active Directory  Enterprise Application  All Applications  change filter: Application type = All
Applications  Select DssDemoApp  Properties
6. Properties  User assignment required = Yes  Save
7. Now add users to Users and Groups and only these users will be able to login to the application.

Java Example:
[Link]
[Link]
app-with-azure-active-directory
[Link]
directory-developer-guide
Calling a Web API from a Daemon Application (server to server call) – Authentication Flow: Client Credentials

To Demonstrate how the Application can use its own Identity (not its loggedin users) to access the WebAPI

Application roles are exposed by web APIs called by daemon applications (that calls your web API on their own
behalf).

16
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

Step1: Azure Portal: Create an Azure AD App for WebAPI.


1. Azure Portal  Azure Active Directory  App Registration  + New Registration, Name=MyWebApi
2. MyWebAPI  Overview  Add an Application ID URI  Set  Application ID
URI=[Link]  Save
3. Note Application (ClientID), Tenant ID.
4. MyWebAPI  Owners  + Add owner  Search and Select for your Id  Select (Only if AD App is created
using VS along with API App)
5. MyWebAPI  App roles  + Create app role  Display Name="access_as_application", Select Application,
Value="access_as_application", Description="any string", Apply
This will edit Manifest as below:
MyWebAPI  Manifest (Edit a below)
"appRoles": [
{
"allowedMemberTypes": [
"Application"
],
"description": "Accesses the MyWebAPI as an application.",
"displayName": "access_as_application",
"id": "fad303c2-d9e0-4c8e-8113-85964ec372fc",
"isEnabled": true,
"lang": null,
"origin": "Application",
"value": "access_as_application"
}

17
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

Step2: Build WebAPI Application


6. Visual Studio: Create a Web API Application
7. Edit [Link]
"AzureAd": {
"Instance": "[Link]
"Domain": "[Link]",
"TenantId": "82d8af3b-d3f9-465c-b724-0fb186cc28c7",
"ClientId": "b34aafc5-2d79-46f7-afbb-e02045766c53",
"Audience": "[Link]
}

8. Add NUGET Package: [Link]


9. Edit [Link]
using [Link];
[Link]([Link], "AzureAd");
[Link]();
[Link]();
10. Use [Authorize] attribute whereever required. (Either for API Controller or it’s action methods)

Step3: Azure Portal: Create an Azure AD App for Console Application.


1. Azure Portal  Azure Active Directory  App Registration  + New Registration, Name=MyConApp
2. API permission  + Add a permission 
a. + Add a permission  Microsoft Graph  Application permission  Expand Users  Check
[Link]  Add permissions
b. + Add a permission  My APIs Tab  Select MyWebAPI, select Application permission and check
access_as_aplication  Add permissions.
c. Click Grand admin consent for the (AD) Directory.

Step 4: Develop the Console Application to use Secure API


Add NuGet Package reference [Link]
18
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

using System;
using [Link];
using [Link];
using [Link];
using [Link];

class Program
{
private const string _clientId = "<client id of AD App for ConApp";
private const string _tenantId = "82d8af3b-d3f9-465c-b724-0fb186cc28c7";
public static async Task Main(string[] args)
{
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder
.Create(_clientId)
.WithAuthority([Link], _tenantId)
.WithClientSecret("A2Y_CQWo_NxtNY9..WNOolLe7k8y318uZ2")
.Build();

//Invoding Microsoft Graph API


string[] scopes = { "[Link] };
AuthenticationResult result = await [Link](scopes).ExecuteAsync();
[Link]($"Token:\t{[Link]}");

string endpoint = "[Link]


var client = new HttpClient();
var authHeader = new AuthenticationHeaderValue("Bearer", [Link]);
[Link] = authHeader;
var response = await [Link](endpoint);
string json = await [Link]();
[Link](json);

//Invoding Custom Web API

19
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

var client1 = new HttpClient();


string[] scopes1 = { "[Link] };
var result1 = await [Link](scopes1).ExecuteAsync();
client1 = new HttpClient();
var authHeader1 = new AuthenticationHeaderValue("Bearer", [Link]);
[Link] = authHeader1;
string endpoint1 = "[Link] //URL of WebAPI
var response1 = await [Link](endpoint1);
string json1 = await [Link]();
[Link](json1);
}
}

Java Example:
[Link]

Invoking a Secure API from Client using Users Identity - Authentication Flow: Interactive
To Demonstrate how the Application can use its logged-in users identity to access the WebAPI

Step1: Create a New AD Application for Web API


1. Select App registrations, and then select New registration
a) Name = MyWebAPI
b) Supported account types = Accounts in this organizational directory only (Personal Directory only -
Single tenant)
c) Redirect URIs = <Leave it as blank> (Web APIs don't need to register a redirect URI because no user is
interactively signed in)
2. Overview  Application ID URL = [Link]
3. Expose an API  + Add a Scope 
a) for Scope name use user_impersonation
b) Ensure the Admins and users option is selected for Who can consent
c) in Admin consent display name type Access My Web API as a Admin
d) in Admin consent description type Accesses the My Web API as a Admin

20
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

e) in User consent display name type Access My Web API as a user


f) in User consent description type Accesses the My Web API as a user
g) Keep State as Enabled
h) Select Add scope

Step2: Build WebAPI Application


1. Visual Studio: Create a Web API Application
a. Write a method which returns [Link](claim => [Link] == "name").Value
2. Edit [Link]
"AzureAd": {
"Instance": "[Link]
"Domain": "[Link]",
"TenantId": "82d8af3b-d3f9-465c-b724-0fb186cc28c7",
"ClientId": "b34aafc5-2d79-46f7-afbb-e02045766c53",
"Audience": [Link]
}
3. Edit [Link]
public void ConfigureServices(IServiceCollection services)
{
[Link](Configuration, "AzureAd");
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
[Link]();
[Link]();
}
4. Use [Authorize] attribute whereever required.
5. Add the following to WebAPI Method to check if the request has the scope user_impersonation or not
[HttpGet]
public IEnumerable<WeatherForecast> Get()
21
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

{
//[Link](claim => [Link] == "name").Value
var apiClaim = [Link](c => [Link] == "[Link] &&
[Link]("user_impersonation")).FirstOrDefault();
if (apiClaim == null)
{
throw new ApplicationException("Unauthorized-The Scope claim does not contain 'user_impersonation' or
scope claim not found");
}

var rng = new Random();


return [Link](1, 5).Select(index => new WeatherForecast
{
Date = [Link](index),
TemperatureC = [Link](-20, 55),
Summary = Summaries[[Link]([Link])]
})
.ToArray();
}

Step3: Create an Azure AD Application for Client Application (Mobile App or Console App)
1. Azure Portal  Active Directory  App Registrations  New registration  Name=MyConApp
2. Name = MyDemoApp, Supported Account Types = Accounts in this organizational directory only
3. Redirect URL: Public client/native (mobile & desktop), [Link]
4. API Permissions  Add a permission  My APIs  Select MyWebAPI  Check user_impersonation  Add
permission.

Step4: .NET Core Console Application


Add reference to NuGet package [Link]
using System;
using [Link];
using [Link];

22
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

using [Link];
using [Link];

class Program
{
private const string _clientId = "2226001b-e403-4f74-b9b6-76133a83d990";
private const string _tenantId = "82d8af3b-d3f9-465c-b724-0fb186cc28c7";
public static async Task Main(string[] args)
{
IPublicClientApplication app = PublicClientApplicationBuilder
.Create(_clientId)
.WithAuthority([Link], _tenantId)
.WithRedirectUri("[Link]
.Build();

//Invoking Graph API


string[] scopes = { "[Link]" };
AuthenticationResult result = await [Link](scopes).ExecuteAsync();
[Link]($"Token:\t{[Link]}");
string endpoint = "[Link]
var client = new HttpClient();
var authHeader = new AuthenticationHeaderValue("Bearer", [Link]);
[Link] = authHeader;
var response = await [Link](endpoint);
string json = await [Link]();
[Link](json);

//Custom API
string[] scopes1 = { "[Link] };
AuthenticationResult result1 = await [Link](scopes1).ExecuteAsync();
var client1 = new HttpClient();
var authHeader1 = new AuthenticationHeaderValue("Bearer", [Link]);

23
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

[Link] = authHeader1;
string endpoint1 = "[Link] //URL of WebAPI
var response1 = await [Link](endpoint1);
string json1 = await [Link]();
[Link](json1);
}
}
Note: The AcquireTokenSilent will return the token it already has in cache if it is still valid or get a new one using
refresh token or cookies in case implicit id_token. You can only make this call however if you are sure that you
already have an access token or use has already been authenticated by a previous non-silent acquire token call.

Accessing Secure Web API from Web App using Logged-In Users Identity

24
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

Build WebAPI and WebApp and Test without security


4. Create New [Link] Core Web Application (Web API Template). The template auto generates
WeatherForecast API Controller and we will use the same for our demo.
5. Create New [Link] Core Web Application (MVC Contoller Template)
6. Add the following to [Link] of WebApp (Assuming that 44342 is the SSL port of Web API)
"APIUrl": "[Link]
7. Add to the project WeatherForecast class (Copy from Web API project and change the namespace)
8. Edit HomeController, Index method
HttpClient httpClient = new HttpClient();
string url = _config["ApiUrl"] + "weatherforecast";
var request = new HttpRequestMessage()
{
RequestUri = new Uri(url)
};
IEnumerable<WeatherForecast> cols = null;
using (var response = [Link](request).Result)
{
cols = [Link]<IEnumerable<WeatherForecast>>([Link]
nc().Result);
};
return View(cols);
9. Right Click on Index and Add a New View – Razor View
a) View Name = Index
b) Template = List
c) Model class = WeatherForecast
d) Add
10. Run both WebAPI and WebApp and test the application.

Create a New AD Application for Web API


11. Select App registrations, and then select New registration
d) Name = MyWebAPI

25
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

e) Supported account types = Accounts in this organizational directory only (Personal Directory only -
Single tenant)
f) Redirect URI = <Leave it as blank>
12. Authentication  Under Implicit Grant check = ID tokens
13. Overview  Application ID URI = [Link]
14. Expose an API  + Add a Scope 
i) for Scope name use user_impersonation
j) Ensure the Admins and users option is selected for Who can consent
k) in Admin consent display name type Access My Web API as a Admin
l) in Admin consent description type Accesses the My Web API as a Admin
m) in User consent display name type Access My Web API as a user
n) in User consent description type Accesses the My Web API as a user
o) Keep State as Enabled
p) Select Add scope

Secure the WebApp Application


Create a New AD Application for Web App
15. Select App registrations, and then select New registration
g) Name = MyWebApp
h) Supported account types = Accounts in this organizational directory only (Personal Directory only -
Single tenant)
i) Redirect URI = [Link]
16. Authentication 
1. Logout URL = [Link]
2. Under Implicit Grant check = ID tokens
17. API Permissions  Add a permission  My APIs  Select MyWebAPI  Check user_impersonation  Add
permission.
18. Certificate & Secrets  Create a copy Client Secret

Update the WebAPI Project


19. Add reference to NuGet Package - [Link]
20. Update [Link]

26
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

"AzureAd": {
"Instance": "[Link]
"Domain": "[Link]",
"TenantId": "82d8af3b-d3f9-465c-b724-0fb186cc28c7",
"ClientId": "2f2e4e4e-aa57-4e07-83bd-a9853b55eb67"
"Audience": "[Link]
}
21. To [Link]  ConfigureServices method add the following line
[Link](Configuration, "AzureAd");
22. Add the following to Configure method
[Link]();
[Link]();

23. A common requirement for web APIs is to validate the "scopes" present in the token to ensure that the user
has consented to the permissions required to access the WebAPI.
[HttpGet]
[Authorize]
public IEnumerable<WeatherForecast> Get()
{
var apiClaim = [Link](c => [Link] == "[Link] &&
[Link]("user_impersonation")).FirstOrDefault();
if (apiClaim == null)
{
throw new ApplicationException("Unauthorized-
The Scope claim does not contain 'user_impersonation' or scope claim not found");
}
var rng = new Random();
return [Link](1, 5).Select(index => new WeatherForecast
{
Date = [Link](index),
TemperatureC = [Link](-20, 55),
Summary = Summaries[[Link]([Link])]
27
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

})
.ToArray();
}

Update the WebApp Project


24. Add reference to NuGet packages
a) [Link]
b) [Link]
25. Edit [Link]
"AzureAd": {
"Instance": "[Link]
"Domain": "[Link]",
"TenantId": "82d8af3b-d3f9-465c-b724-0fb186cc28c7",
"ClientId": "06cfc5e9-b404-4bc1-90de-217a98a188b7",
"CallbackPath": "/signin-oidc",
"SignedOutCallbackPath": "/signout-oidc",
"ClientSecret": "d2-62sab3_T86yz0wWCl7XvDbWf2DH~-r_"
}
26. Edit ConfigureServices in [Link]
[Link](Configuration, "AzureAd")
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { "[Link]
[Link]/MyWebAPI/user_impersonation" })
.AddInMemoryTokenCaches();
[Link]().AddMicrosoftIdentityUI();
27. Add the following to Configure method
[Link]();
[Link]();
28. Edit HomeController as below
public class HomeController : Controller
{
IConfiguration _config;

28
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

readonly ITokenAcquisition _tokenAcquisition;


public HomeController(ILogger<HomeController> logger, IConfiguration config, ITokenAcquisition tokenAcq
uisition)
{
_config = config;
_tokenAcquisition = tokenAcquisition;
}
public IActionResult Index()
{
return View();
}
[AuthorizeForScopes(Scopes = new[] { "[Link]
mpersonation" })]
public async Task<IActionResult> WeatherForecast()
{
HttpClient httpClient = new HttpClient();
string[] scopes = new string[] { "[Link]
onation" };
string token = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes);
[Link] = new AuthenticationHeaderValue("Bearer", token);

string url = _config["ApiUrl"] + "weatherforecast";


var request = new HttpRequestMessage()
{
RequestUri = new Uri(url)
};
IEnumerable<WeatherForecast> cols = null;
using (var response = [Link](request).Result)
{
cols = [Link]<IEnumerable<WeatherForecast>>([Link]
Async().Result);
};

29
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

return View(cols);
}
}

(Optional) Pre-authorize your client application


One of the ways to allow users from other directories to access your Web API is by pre-authorizing the client
applications to access your Web API by adding the Application Ids from client applications in the list of pre-
authorized applications for your Web API. By adding a pre-authorized client, you will not require user to consent
to use your Web API. Follow the steps below to pre-authorize your Web Application::
1. Go back to the Application registration portal and open the properties of your MyWebAPI.
2. In the Expose an API section, click on Add a client application under the Authorized client applications
section.
3. In the Client ID field, paste the application ID of the TodoListClient application.
4. In the Authorized scopes section, select the scope for this Web API api://<Application
ID>/user_impersonation
5. Press the Add application button at the bottom of the page.

Role-based authorization
Role-based authorization is an authorization approach in which user permissions are managed and enforced by an
application based on user roles. If a user has a role that is required to perform an action, access is granted;
otherwise, access is denied. When an identity is created, it may belong to one or more roles. For example, Holly
may belong to the Administrator and User roles, whereas Adam may belong only to the User role. How these roles
are created and managed depends on the backing store of the authorization process.

Implementing Roles using Azure AD App Roles


a) The SaaS (Security as a Service) provider defines the application roles by adding them to the application
manifest.
b) After a customer signs up, an admin for the customer's AD directory assigns users to the roles.
c) When a user signs in, the user's assigned roles are sent as claims.

Advantages of this approach:


 Simple programming model.
30
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

 Roles are specific to the application. The role claims for one application are not sent to another application.
 If the customer removes the application from their AD tenant, the roles go away.
 The application doesn't need any extra Active Directory permissions, other than reading the user's profile.
Drawbacks:
 Customers without Azure AD Premium cannot assign security groups to roles. For these customers, all user
assignments must be done by an AD administrator.
 If you have a backend web API, which is separate from the web app, then role assignments for the web app
don't apply to the web API.
Steps To Implement
Azure AD  App registrations  Select the app  Manifest  Edit the Manifest (Search “appRoles” and edit)
"appRoles": [
{
"allowedMemberTypes": [
"User"
],
"description": "This is Demo Role1",
"displayName": "DemoRole1",
"id": "1b4f816e-5eaf-48b9-8613-7923830595ty",
"isEnabled": true,
"value": "DemoRole1"
},
{
"allowedMemberTypes": [
"User"
],
"description": "This is Demo Role2",
"displayName": "DemoRole2",
"id": "c20e145e-5459-4a6c-a074-b942bbd4cab1",
"isEnabled": true,
"value": "DemoRole2"
}
],

31
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

Note: The value property appears in the role claim. The id property is the unique identifier for the defined role.
Always generate a new GUID value for id.

Assign users.
When a new customer signs up, the application is registered in the customer's AD tenant. At this point, an AD
admin for that tenant can assign users to roles.
Azure AD  Enterprise Application  Select the Application  Users and groups  Add user  Select User and
Select Role

Role-Based authorization in [Link]


Get role claims. When a user signs in, the application receives the user's assigned role(s) in a claim with type
[Link] OR [Link]

Roles are exposed to the developer through the IsInRole method on the ClaimsPrincipal class. Role-based Instead,
write code that checks whether a particular claim value is present:

bool isHavingDemoRole1 = [Link]("DemoRole1").ToString()


OR
bool isHavingDemoRole1 = ((ClaimsPrincipal)User).HasClaim([Link], "DemoRole1")

Authorization checks are declarative—the developer embeds them within their code, against a controller or an
action within a controller, specifying roles that the current user must be a member of to access the requested
resource.
For example, the following code limits access to any actions on the DemoController to users who are members of
the DemoRole1 role:
[Authorize(Roles = "DemoRole1")]
public class DemoController : Controller { }

You can specify multiple roles as a comma separated list:


[Authorize(Roles = "DemoRole1, DemoRole2")]
public class DemoController : Controller { }
This controller would be accessible only by users who are members of the DemoRole1 role or the DemoRole2 role.

32
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

If you apply multiple attributes, an accessing user must be a member of all the roles specified. The following
sample requires that a user be a member of both the DemoRole1 and DemoRole2 roles:
[Authorize(Roles = "DemoRole1")]
[Authorize(Roles = "DemoRole2")]
public class ControlPanelController : Controller { }

You can further limit access by applying additional role authorization attributes at the action level:
[Authorize(Roles = "DemoRole1, DemoRole2")]
public class ControlPanelController : Controller
{
public ActionResult SetTime()
{}
[Authorize(Roles = "DemoRole2")]
public ActionResult ShutDown()
{}
}
In the previous code snippet, members of either the DemoRole1 role or the DemoRole2 role can access the
controller and the SetTime action, but only members of the DemoRole2 role can access the ShutDown action.

You can also lock down a controller but allow anonymous, unauthenticated access to individual actions:
[Authorize]
public class ControlPanelController : Controller
{
public ActionResult SetTime()
{}
[AllowAnonymous]
public ActionResult Login()
{}
}

Policy Syntax

33
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

In [Link] Core Role requirements can also be expressed using the Policy syntax, where a developer registers a
policy at startup as part of the authorization service configuration. This normally occurs in ConfigureServices() in
your [Link] file:
public void ConfigureServices(IServiceCollection services)
{
[Link]();
[Link](options => {
[Link]("RequireAdministratorRole", policy => [Link]("Administrator"));
});
}

Policies are applied using the Policy property on the AuthorizeAttribute attribute:
[Authorize(Policy = "RequireAdministratorRole")]
public IActionResult Shutdown()
{
return View();
}

If you want to specify multiple allowed roles in a requirement, you can specify them as parameters to the
RequireRole method:
[Link]("ElevatedRights", policy => [Link]("Administrator", "PowerUser",
"BackupAdministrator"));
This example authorizes users who belong to the Administrator, PowerUser, or BackupAdministrator roles.

Roles using an application role manager


With this approach, application roles are not stored in Azure AD at all. Instead, the application stores the role
assignments for each user in its own DB — for example, using the RoleManager class in [Link] Identity.
Advantages:
 The app has full control over the roles and user assignments.
Drawbacks:
 More complex, harder to maintain.
 Cannot use AD security groups to manage role assignments.

34
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

 Stores user information in the application database, where it can get out of sync with the tenant's AD
directory, as users are added or removed.

Claims Based Authorization


What is Claims?
 When an identity is created, it may be assigned one or more claims issued by a trusted party. A claim is a
name/value pair that represents what the subject is and not what the subject can do. For example, you may
have a driver's license issued by a local driving license authority. Your driver's license has your date of birth on
it. In this case, the claim name would be DateOfBirth, the claim value would be your date of birth — for
example, June 8, 1970 — and the issuer would be the driving license authority. An identity can contain
multiple claims with multiple values and can contain multiple claims of the same type.
 Claims-based authorization is an approach where the authorization decision to grant or deny access is based
on arbitrary logic that uses data available in claims to make the decision. Claims-based authorization, at its
simplest, checks the value of a claim and allows access to a resource based on that value. For example, if you
want access to a night club, the authorization process might be: The door security officer evaluates the value
of your date of birth claim and whether they trust the issuer (the driving license authority) before granting you
access.
 In a relying party application, authorization determines what resources an authenticated identity is allowed to
access and what operations it is allowed to perform on those resources. Improper or weak authorization leads
to information disclosure and data tampering.
 Claim-based authorization checks are declarative—the developer embeds them within their code, against a
controller or an action within a controller, specifying claims that the current user must possess and optionally
the value the claim must hold to access the requested resource. Claims requirements are policy based; the
developer must build and register a policy expressing the claims requirements.

Claims-based authorization in Microsoft [Link]


To get the list of claims in the authenticated request:
foreach (var claim in (([Link])[Link]).Claims)
{
[Link] += [Link] + ":" + [Link] + "<br>";
}

35
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

bool hasRoleClaim = ((ClaimsPrincipal)User).HasClaim(c => [Link] == [Link]);


OR
bool isHavingDemoRole1 = ((ClaimsPrincipal)User).HasClaim([Link], "DemoRole1")

Using Policy in [Link] Core


The simplest type of claim policy looks for the presence of a claim and doesn't check the value.
First, you need to build and register the policy. This takes place as part of the authorization service configuration,
which normally takes place in ConfigureServices() in your [Link] file:
public void ConfigureServices(IServiceCollection services)
{
[Link]();
[Link](options => {
[Link]("issuer", policy => [Link]("iss"));
});
}
In this case, the issuer policy checks for the presence of an iss claim on the current identity. You then apply the
policy using the Policy property on the

AuthorizeAttribute attribute to specify the policy name:


[Authorize(Policy = "issuer")]
public IActionResult VacationBalance() { return View(); }

If you have a controller that's protected by the AuthorizeAttribute attribute but want to allow anonymous access
to particular actions, you apply the AllowAnonymousAttribute attribute:
[Authorize(Policy = "EmployeeOnly")]
public class VacationController : Controller
{
public ActionResult VacationBalance()
{}
[AllowAnonymous]
public ActionResult VacationPolicy()
{}

36
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

Most claims come with a value. You can specify a list of allowed values when creating the policy. The following
example succeeds only for employees whose employee number is 1, 2, 3, 4 or 5:
public void ConfigureServices(IServiceCollection services)
{
[Link]();
[Link](options => {
[Link]("ValidIssuers", policy => [Link]("iss",
"[Link]
"[Link]
});
}
[Authorize(Policy = "ValidIssuers")]
public void Foo()
{}

Microsoft Graph API


You can use the Microsoft Graph API to interact with the data of millions of users in the Microsoft cloud. Use
Microsoft Graph to build apps for organizations and consumers that connect to a wealth of resources,
relationships, and intelligence, all through a single endpoint: [Link]
You can also get valuable insights and intelligence about the data from Microsoft Graph. For example, you can get
the popular files trending around a particular user, or get the most relevant people around a user.

37
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

What can you do with Microsoft Graph?


You can use Microsoft Graph to build experiences around the user's unique context to help them be more
productive.
Imagine an app that...
 Looks at your next meeting and helps you prepare for it by providing profile information for attendees,
including their job titles and who they work with, as well as information on the latest documents and projects
they're working on.
 Scans your calendar, and suggests the best times for the next team meeting.
 Fetches the latest sales projection chart from an Excel file in your OneDrive and lets you update the forecast in
real time, all from your phone.
 Subscribes to changes in your calendar, sends you an alert when you’re spending too much time in meetings,
and provides recommendations for the ones you could miss or delegate based on how relevant the attendees
are to you.
 Helps you sort out personal and work information on your phone; for example, by categorizing pictures that
should go to your personal OneDrive and business receipts that should go to your OneDrive for Business.

Microsoft Graph REST API


One base URL for all queries:
 Structure: [Link]
 Basic API: [Link]
Relative resource URLs (not all inclusive):
38
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

 /me
o /me/messages
o /me/drive
 /user
 /group

1. For the CRUD methods GET and DELETE, no request body is required.
2. The POST, PATCH, and PUT methods require a request body, usually specified in JSON format, that contains
additional information, such as the values for properties of the resource.

Sample URL's:
 [Link]
 [Link]
 [Link]
 [Link]
skills

Sample Explorer Project: [Link]

Microsoft Graph SDK


The Microsoft Graph client is designed to make it simple to make calls to Microsoft Graph.
 SDK to interact with the Microsoft Graph using easy-to-parse classes and properties
 Available on NuGet
o [Link]: used to query Microsoft Graph
o [Link]: used to plug in to [Link] for authentication

Walkthrough
1. Configure Permission in Azure AD Application:
a) Go to App Registration  Select the App  API Permission
b) + Add a permission  Microsoft Graph  Delegated permissions
c) Check [Link] (Read all users full profiles)  Add permissions
2. Create a Console Application
39
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

a) Add the NuGet Packages


 dotnet add package [Link]
 dotnet add package [Link] --version 1.0.0-preview.2
b) Edit Main as below:
using [Link];
using [Link];
using [Link];
using System;
using [Link];

class Program
{
private const string _clientId = "fd5b684c-2d9d-4160-873a-b7e92b784ea1";
private const string _tenantId = "ef404960-95a9-49fb-be86-72acd7a3bc27";
public static async Task Main (string[] args)
{
var app = PublicClientApplicationBuilder
.Create(_clientId)
.WithAuthority([Link], _tenantId)
.WithRedirectUri("[Link]
.Build();

string[] scopes = { "[Link]", "[Link]" };


var provider = new InteractiveAuthenticationProvider(app, scopes);
GraphServiceClient client = new GraphServiceClient(provider);
User me = await [Link]().GetAsync();
[Link]($"Display Name:\t{[Link]}");

var users = await [Link]().GetAsync();


foreach (var user in users)
{
[Link]([Link]);

40
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)
Deccansoft Software Services – Microsoft Azure Azure Active Directory

}
}
}

More Microsoft Graph Tutorials: [Link]

Authenticating to and querying Microsoft Graph by using MSAL and .NET SDKs
[Link]
DevelopingSolutionsforMicrosoftAzure/blob/master/Instructions/Labs/AZ-204_06_lab.md

41
Deccansoft Software Services [Link]: 153, A/4, Balamrai, Secunderabad-500003 TELANGANA, NDIA.
[Link] | [Link]
Phone: +91 40 2784 1517 OR +91 8008327000 (INDIA)

You might also like