Azure Active Directory: Understanding Different Account Types

Overview

Azure Active Directory (Azure AD) is a cloud-based identity and access management service offered by Microsoft. It serves as the backbone for managing user identities, securing applications, and controlling access to Azure resources. Azure AD supports various account types, each with its purpose and capabilities. In this article, we will explore the different account types in Azure AD, their features, and how they can be leveraged in your Azure environment.

Azure AD Work or School Accounts

Azure AD Work or School Accounts are user accounts created and managed by organizations within Azure Active Directory (Azure AD). These accounts are typically associated with an organization's Active Directory and are used for work or school-related purposes.

With Azure AD Work or School Accounts, users gain access to various company resources, including applications, files, email, and collaboration tools within their organization's Azure AD tenant. They can sign in to these accounts using their organizational email addresses and passwords, providing a seamless and secure authentication experience.

Azure AD Work or School Accounts offer several benefits for organizations. They enable centralized management of user identities and access control, ensuring that only authorized individuals can access sensitive resources. Administrators can assign roles, permissions, and group memberships to these accounts, allowing fine-grained control over access privileges.

These accounts support single sign-on (SSO), enabling users to access multiple applications and services with a single set of credentials. This streamlines the user experience and reduces the burden of remembering multiple usernames and passwords.

Azure AD Work or School Accounts also provide a foundation for implementing security measures such as multi-factor authentication (MFA) and conditional access policies. These features add an extra layer of protection to user accounts, ensuring that only trusted individuals can access organizational resources.

Azure AD Work or School Accounts are essential for organizations that want to establish a secure and centralized identity management system. They provide a seamless user experience, strong authentication mechanisms, and granular access control, all while integrating with other Azure services and applications.

Code example

Showcasing how we can interact with Azure AD Work or School Accounts using various programming languages and Azure AD Graph API.

C# Example using Microsoft Graph SDK

using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;

// Define the Azure AD authentication settings
string clientId = "<your_client_id>";
string clientSecret = "<your_client_secret>";
string tenantId = "<your_tenant_id>";

// Create an instance of the GraphServiceClient using client credentials
var client = new GraphServiceClient(new ClientCredentialProvider(
    new ClientCredential(clientId, clientSecret)));

// Retrieve a specific user's details
string userId = "<user_object_id>";
var user = await client.Users[userId].Request().GetAsync();

// Print the user's display name
Console.WriteLine($"User Display Name: {user.DisplayName}");

PowerShell Example using AzureAD module

# Install AzureAD module if not already installed
Install-Module -Name AzureAD

# Connect to Azure AD using your credentials
Connect-AzureAD

# Retrieve a specific user's details
$userId = "<user_object_id>"
$user = Get-AzureADUser -ObjectId $userId

# Print the user's display name
Write-Output "User Display Name: $($user.DisplayName)"

Node.js Example using the MSAL library

const { PublicClientApplication } = require('@azure/msal-node');

// Define the Azure AD authentication settings
const clientId = "<your_client_id>";
const authority = "https://login.microsoftonline.com/<your_tenant_id>";

// Create a public client application instance
const pca = new PublicClientApplication({
    auth: {
        clientId,
        authority
    }
});

// Acquire an access token and call the Microsoft Graph API
const getTokenAndCallGraphAPI = async () => {
    const tokenRequest = {
        scopes: ['User.Read'],
    };

    // Retrieve an access token
    const response = await pca.acquireTokenByUsernamePassword(tokenRequest, "<username>", "<password>");
    const accessToken = response.accessToken;

    // Call the Microsoft Graph API to get user details
    const fetch = require('node-fetch');
    const url = 'https://graph.microsoft.com/v1.0/me';
    const options = {
        method: 'GET',
        headers: {
            Authorization: `Bearer ${accessToken}`
        }
    };

    // Fetch the user details
    const userResponse = await fetch(url, options);
    const user = await userResponse.json();

    // Print the user's display name
    console.log(`User Display Name: ${user.displayName}`);
};

getTokenAndCallGraphAPI();

These above code examples demonstrate how to authenticate and retrieve details of Azure AD Work or School Accounts using different programming languages and authentication mechanisms. We can further explore the Azure AD Graph API or Microsoft Graph API documentation to discover more operations and capabilities available for Azure AD Work or School Accounts.

Azure AD Guest Accounts

Azure AD Guest Accounts are accounts created in Azure Active Directory (Azure AD) for external users who need to access resources within an Azure AD tenant. These accounts are commonly used for collaboration purposes with external partners, vendors, clients, or any user who does not belong to the organization's primary directory.

Azure AD Guest Accounts provide a means to grant limited access to specific resources while maintaining control over permissions and user management. The inviting organization can extend invitations to external users, allowing them to access applications, files, and other resources within the Azure AD tenant.

Below are code examples showcasing how to manage Azure AD Guest Accounts using various programming languages and Azure AD Graph API.

C# Example using Microsoft Graph SDK

using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;

// Define the Azure AD authentication settings
string clientId = "<your_client_id>";
string clientSecret = "<your_client_secret>";
string tenantId = "<your_tenant_id>";

// Create an instance of the GraphServiceClient using client credentials
var client = new GraphServiceClient(new ClientCredentialProvider(
    new ClientCredential(clientId, clientSecret)));

// Invite a guest user to the Azure AD tenant
var invitation = new Invitation
{
    InvitedUserEmailAddress = "<guest_user_email>",
    InviteRedirectUrl = "<redirect_url>"
};

await client.Invitations.Request().AddAsync(invitation);

// Retrieve the invited guest user's details
var user = await client.Users.Request()
    .Filter($"userPrincipalName eq '{invitation.InvitedUserEmailAddress}'")
    .GetAsync();

// Print the invited guest user's display name
Console.WriteLine($"Invited Guest User Display Name: {user.FirstOrDefault()?.DisplayName}");

PowerShell Example using AzureAD module

# Install AzureAD module if not already installed
Install-Module -Name AzureAD

# Connect to Azure AD using your credentials
Connect-AzureAD

# Invite a guest user to the Azure AD tenant
$invitation = New-AzureADMSInvitation -InvitedUserEmailAddress "<guest_user_email>"

# Retrieve the invited guest user's details
$user = Get-AzureADUser -Filter "userPrincipalName eq '$($invitation.InvitedUserEmailAddress)'"

# Print the invited guest user's display name
Write-Output "Invited Guest User Display Name: $($user.DisplayName)"

Node.js Example using the MSAL library

const { PublicClientApplication } = require('@azure/msal-node');

// Define the Azure AD authentication settings
const clientId = "<your_client_id>";
const authority = "https://login.microsoftonline.com/<your_tenant_id>";

// Create a public client application instance
const pca = new PublicClientApplication({
    auth: {
        clientId,
        authority
    }
});

// Acquire an access token and invite a guest user
const inviteGuestUser = async () => {
    const tokenRequest = {
        scopes: ['User.Invite.All'],
    };

    // Retrieve an access token
    const response = await pca.acquireTokenByUsernamePassword(tokenRequest, "<username>", "<password>");
    const accessToken = response.accessToken;

    // Invite a guest user
    const fetch = require('node-fetch');
    const url = 'https://graph.microsoft.com/v1.0/invitations';
    const options = {
        method: 'POST',
        headers: {
            Authorization: `Bearer ${accessToken}`,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            invitedUserEmailAddress: "<guest_user_email>",
            inviteRedirectUrl: "<redirect_url>"
        })
    };

    // Invite the guest user
    const invitationResponse = await fetch(url, options);
    const invitation = await invitationResponse.json();

    // Print the invited guest user's display name
    console.log(`Invited Guest User Display Name: ${invitation.invitedUser.displayName}`);
};

inviteGuestUser();

The code examples above demonstrate how to invite and manage Azure AD Guest Accounts programmatically using different programming languages and authentication mechanisms. We can further explore the Azure AD Graph API or Microsoft Graph API documentation to discover more operations and capabilities available for Azure AD Guest Accounts.

Azure AD B2B Collaboration

Azure AD B2B Collaboration enables organizations to securely collaborate with external partners by granting them access to specified resources within their Azure Active Directory (Azure AD) tenant. It provides a seamless and controlled approach for sharing applications, data, and other resources with users from partner organizations.

Below are code examples showcasing how to manage Azure AD B2B Collaboration using various programming languages and Azure AD Graph API.

C# Example using Microsoft Graph SDK

using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;

// Define the Azure AD authentication settings
string clientId = "<your_client_id>";
string clientSecret = "<your_client_secret>";
string tenantId = "<your_tenant_id>";

// Create an instance of the GraphServiceClient using client credentials
var client = new GraphServiceClient(new ClientCredentialProvider(
    new ClientCredential(clientId, clientSecret)));

// Invite an external user from another organization to collaborate
var invitation = new Invitation
{
    InvitedUserEmailAddress = "<external_user_email>",
    InviteRedirectUrl = "<redirect_url>",
    InviteAdditionalData = new Dictionary<string, object>
    {
        { "invitedUserDisplayName", "<external_user_display_name>" }
    }
};

await client.Invitations.Request().AddAsync(invitation);

// Retrieve the invited external user's details
var user = await client.Users.Request()
    .Filter($"userPrincipalName eq '{invitation.InvitedUserEmailAddress}'")
    .GetAsync();

// Print the invited external user's display name
Console.WriteLine($"Invited External User Display Name: {user.FirstOrDefault()?.DisplayName}");

PowerShell Example using AzureAD module

# Install AzureAD module if not already installed
Install-Module -Name AzureAD

# Connect to Azure AD using your credentials
Connect-AzureAD

# Invite an external user from another organization to collaborate
$invitation = New-AzureADMSInvitation -InvitedUserEmailAddress "<external_user_email>" -InviteRedirectUrl "<redirect_url>"

# Retrieve the invited external user's details
$user = Get-AzureADUser -Filter "userPrincipalName eq '$($invitation.InvitedUserEmailAddress)'"

# Print the invited external user's display name
Write-Output "Invited External User Display Name: $($user.DisplayName)"

Node.js Example using the MSAL library

const { PublicClientApplication } = require('@azure/msal-node');

// Define the Azure AD authentication settings
const clientId = "<your_client_id>";
const authority = "https://login.microsoftonline.com/<your_tenant_id>";

// Create a public client application instance
const pca = new PublicClientApplication({
    auth: {
        clientId,
        authority
    }
});

// Acquire an access token and invite an external user to collaborate
const inviteExternalUser = async () => {
    const tokenRequest = {
        scopes: ['User.Invite.All'],
    };

    // Retrieve an access token
    const response = await pca.acquireTokenByUsernamePassword(tokenRequest, "<username>", "<password>");
    const accessToken = response.accessToken;

    // Invite an external user to collaborate
    const fetch = require('node-fetch');
    const url = 'https://graph.microsoft.com/v1.0/invitations';
    const options = {
        method: 'POST',
        headers: {
            Authorization: `Bearer ${accessToken}`,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            invitedUserEmailAddress: "<external_user_email>",
            inviteRedirectUrl: "<redirect_url>",
            invitedUserDisplayName: "<external_user_display_name>"
        })
    };

    // Invite the external user
    const invitationResponse = await fetch(url, options);
    const invitation = await invitationResponse.json();

    // Print the invited external user's display name
    console.log(`Invited External User Display Name: ${invitation.invitedUser.displayName}`);
};

inviteExternalUser();

The code examples above I have given demonstrate how to invite and manage Azure AD B2B Collaboration users programmatically using different programming languages and authentication mechanisms. You can further explore the Azure AD Graph API or Microsoft Graph API documentation to discover more operations and capabilities available for Azure AD B2B Collaboration.

Azure AD Managed Service Accounts

Azure AD Managed Service Accounts are a type of service account provided by Azure Active Directory (Azure AD) that are designed to securely manage and automate the lifecycle of applications and services. These accounts are ideal for running non-human identity-based services such as applications, scripts, and services that require automated authentication to access Azure resources.

Below are code examples and script examples showcasing how to work with Azure AD Managed Service Accounts.

PowerShell Example for Creating a Managed Service Account

# Install the AzureADPreview module if not already installed
Install-Module -Name AzureADPreview

# Connect to Azure AD using your credentials
Connect-AzureAD

# Create a new Managed Service Account
$managedServiceAccount = New-AzureADManagedServiceAccount -AccountDisplayName "MyManagedServiceAccount" `
    -ServicePrincipalNames "http://myapp" -AccountEnabled $true

# Retrieve the Managed Service Account details
$managedServiceAccount


Azure CLI Example for creating a Managed Service Account
# Create a new Managed Service Account
az ad sp create-for-rbac --name "http://myapp" --skip-assignment

Python Example using the Microsoft Graph API and the msal library

from msal import ConfidentialClientApplication
# Define the Azure AD authentication settings
client_id = "<your_client_id>"
client_secret = "<your_client_secret>"
tenant_id = "<your_tenant_id>"

# Create a Confidential Client Application instance
app = ConfidentialClientApplication(client_id=client_id, client_credential=client_secret, authority=f"https://login.microsoftonline.com/{tenant_id}")

# Create a new Managed Service Account
managed_service_account = app.initialize_account_for_microsoft_identity_service_principal(name="MyManagedServiceAccount", service_principal_names=["http://myapp"])

# Retrieve the Managed Service Account details
print("Managed Service Account:")
print(managed_service_account)

C# Example using the Microsoft Graph SDK

using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;

// Define the Azure AD authentication settings
string clientId = "<your_client_id>";
string clientSecret = "<your_client_secret>";
string tenantId = "<your_tenant_id>";

// Create an instance of the GraphServiceClient using client credentials
var client = new GraphServiceClient(new ClientCredentialProvider(
    new ClientCredential(clientId, clientSecret)));

// Create a new Managed Service Account
var managedServiceAccount = new ManagedServiceAccount
{
    AccountDisplayName = "MyManagedServiceAccount",
    ServicePrincipalNames = new List<string> { "http://myapp" },
    AccountEnabled = true
};

await client.ManagedServiceAccounts.Request().AddAsync(managedServiceAccount);

// Retrieve the Managed Service Account details
Console.WriteLine($"Managed Service Account:");
Console.WriteLine($"DisplayName: {managedServiceAccount.AccountDisplayName}");
Console.WriteLine($"Service Principal Names: {string.Join(", ", managedServiceAccount.ServicePrincipalNames)}");

The above code examples I have given demonstrate how to create Azure AD Managed Service Accounts using different programming languages and authentication mechanisms such as PowerShell, Azure CLI, Python with the Microsoft Graph API, and C# with the Microsoft Graph SDK. You can further explore the respective documentation and SDKs to discover more operations and functionalities available for Azure AD Managed Service Accounts.

Azure AD Application Service Principals

Azure AD Application Service Principals are objects within Azure Active Directory (Azure AD) that represent applications or services and enable them to authenticate and interact with Azure AD resources. Service Principals provide a secure way to authenticate and authorize applications, allowing them to access resources and perform tasks programmatically.

Azure AD Application Service Principals represent applications or services that need to authenticate and interact with Azure AD resources. Service Principals are associated with specific applications or services, allowing them to perform tasks programmatically without relying on user credentials. They have their own set of credentials or can leverage certificate-based authentication, making them ideal for non-interactive scenarios such as automation, APIs, and back-end services.

PowerShell Example to create an Application Service Principal

# Connect to Azure AD using your credentials
Connect-AzureAD

# Register a new Azure AD Application
$azureAdApplication = New-AzureADApplication -DisplayName "MyApp" -IdentifierUris "https://myapp" -HomePage "https://myapp.com"

# Create a Service Principal for the Azure AD Application
$servicePrincipal = New-AzureADServicePrincipal -AppId $azureAdApplication.AppId

# Retrieve the Service Principal details
$servicePrincipal

Azure CLI Example to create an Application Service Principal

# Register a new Azure AD Application
az ad app create --display-name "MyApp" --identifier-uris "https://myapp" --homepage "https://myapp.com"

# Create a Service Principal for the Azure AD Application
az ad sp create --id "<app_id>"

# Retrieve the Service Principal details
az ad sp show --id "<app_id>"

Python Example using the Microsoft Graph API and the msal library

from msal import ConfidentialClientApplication

# Define the Azure AD authentication settings
client_id = "<your_client_id>"
client_secret = "<your_client_secret>"
tenant_id = "<your_tenant_id>"

# Create a Confidential Client Application instance
app = ConfidentialClientApplication(client_id=client_id, client_credential=client_secret, authority=f"https://login.microsoftonline.com/{tenant_id}")

# Register a new Azure AD Application
application = app.register_application(
    display_name="MyApp",
    identifier_uris=["https://myapp"],
    homepage="https://myapp.com"
)

# Create a Service Principal for the Azure AD Application
service_principal = app.initialize_service_principal(application['appId'])

# Retrieve the Service Principal details
print("Service Principal:")
print(service_principal)

C# Example using the Microsoft Graph SDK

using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;

// Define the Azure AD authentication settings
string clientId = "<your_client_id>";
string clientSecret = "<your_client_secret>";
string tenantId = "<your_tenant_id>";

// Create an instance of the GraphServiceClient using client credentials
var client = new GraphServiceClient(new ClientCredentialProvider(
    new ClientCredential(clientId, clientSecret)));

// Register a new Azure AD Application
var application = new Application
{
    DisplayName = "MyApp",
    IdentifierUris = new List<string> { "https://myapp" },
    Homepage = "https://myapp.com"
};

await client.Applications.Request().AddAsync(application);

// Create a Service Principal for the Azure AD Application
var servicePrincipal = new ServicePrincipal
{
    AppId = application.AppId
};

await client.ServicePrincipals.Request().AddAsync(servicePrincipal);

// Retrieve the Service Principal details
Console.WriteLine($"Service Principal:");
Console.WriteLine($"AppId: {servicePrincipal.AppId}");

The code examples above I have given demonstrate how to create Azure AD Application Service Principals using different programming languages and authentication mechanisms such as PowerShell, Azure CLI, Python with the Microsoft Graph API, and C# with the Microsoft Graph SDK. You can further explore the respective documentation and SDKs to discover more operations and functionalities available for Azure AD Application Service Principals.

Summary

Understanding the different account types in Azure AD is essential for effectively managing user identities, securing applications, and controlling access to Azure resources. Azure AD Work or School Accounts, Guest Accounts, B2B Collaboration, Managed Service Accounts, and Application Service Principals each serve unique purposes and play a crucial role in an organization's identity and access management strategy. By leveraging these account types appropriately, organizations can enhance security, simplify collaboration with external users, and streamline application development and deployment in Azure.