AzureADRead Service Documentation đ
Table of Contents
- Overview & Purpose
- Dependencies & Technologies
- Class Diagram (Mermaid UML)
- Key Functional Areas
- Detailed Method Descriptions
5.1. GetUserADList
5.2. GetSignInActivity
5.3. GetUser
5.4. GetUserDetails
5.5. GetAllUserADList - Data Models
- Error Handling & Return Types
- Thirdâparty Integrations
- Usage Examples
- Conclusion
1. Overview & Purpose
AzureADRead is a service in the IrbyImaging.UI project that:
- Authenticates against Azure AD using clientâcredential flow
- Calls Microsoft Graph to retrieve user profiles & signâin activity
- Augments AD data with internal business data (via
IrbyContext) - Prepares lists for UI dropdowns (e.g.
SelectListItem)
This centralizes all Azure AD reading logic, simplifies controllers, and ensures consistent mapping to an Employee view model.
2. Dependencies & Technologies
| Package / Namespace | Purpose |
|---|---|
Azure.Identity |
ClientSecretCredential & token acquisition |
Microsoft.Graph |
GraphServiceClient to call Microsoft Graph endpoints |
Microsoft.AspNetCore.Mvc.Rendering |
SelectListItem for ASP.NET Core dropdown bindings |
Microsoft.EntityFrameworkCore |
Local DB context (IrbyContext) queries |
Microsoft.Extensions.Configuration |
Reads ClientId, Tenant, ClientSecret from configuration |
Newtonsoft.Json |
JSON serialization (imported but not used directly) |
IrbyImaging.* |
Internal models, view models & utilities |
3. Class Diagram (Mermaid UML)
classDiagram
AzureADRead --> IrbyContext
AzureADRead --> IConfiguration
AzureADRead ..> Employee : returns
AzureADRead ..> List~SelectListItem~ : returns
class AzureADRead {
- IrbyContext _context
- IConfiguration _configuration
+ AzureADRead(IrbyContext, IConfiguration)
+ Task<Employee> GetUserADList(string email)
+ Task<Employee> GetSignInActivity(string name)
+ Task<Employee> GetUser(string username)
+ Employee GetUserDetails(string email)
+ List<SelectListItem> GetAllUserADList(string email)
}
class Employee {
+ Guid UserId
+ string FullName
+ string Title
+ string Department
+ string Email
+ string EmployeeNumber
+ string PhoneNumber
+ DateTime? LastSignInDateTime
+ DateTime? LastNonInteractiveSignInDateTime
+ string JobNumber
}
4. Key Functional Areas
| Functional Area | Description |
|---|---|
| Authentication | Builds ClientSecretCredential using values from IConfiguration |
| Graph Client Initialization | Instantiates GraphServiceClient with credential & scopes |
| User Data Retrieval | Queries user profile & signâin activity from Microsoft Graph |
| Business Data Augmentation | Joins AD data with local DB (IrbyContext.Employees & Jobs) |
| UI Dropdown Population | Builds List<SelectListItem> for active employees |
5. Detailed Method Descriptions
5.1 GetUserADList(string email)
Fetches a user from Azure AD by email, then populates an Employee object with profile & signâin data.
public async Task<Employee> GetUserADList(string email)
{
// 1. Split email to get username
var username = email.Split('@')[0];
// 2. Build credential & Graph client
var graphClient = CreateGraphClient();
// 3. Primary AD fetch
var user = await graphClient.Users[email].GetAsync();
// 4. Secondary fetch (Department + SignInActivity)
var result = await graphClient.Users.GetAsync(cfg =>
{
cfg.QueryParameters.Filter = $"id eq '{user.Id}'";
cfg.QueryParameters.Select = new[] { "displayName", "signInActivity", "Department" };
});
// 5. Map to Employee view model
var emp = new Employee
{
FullName = user.DisplayName,
Title = user.JobTitle,
Department = user.Department,
Email = email,
EmployeeNumber = user.EmployeeId,
PhoneNumber = user.MobilePhone,
UserId = Guid.Parse(user.Id)
};
// 6. Map signInActivity if present
if (result.Value.Any() && result.Value[0].SignInActivity != null)
{
var sa = result.Value[0].SignInActivity;
emp.LastSignInDateTime = sa.LastSignInDateTime?.DateTime;
emp.LastNonInteractiveSignInDateTime = sa.LastNonInteractiveSignInDateTime?.DateTime;
emp.Department = result.Value[0].Department ?? emp.Department;
}
return emp;
}
5.2 GetSignInActivity(string name)
Searches users whose displayName starts with name and returns signâin data.
Note: The returned
Employeeis currently emptyâmapping logic can be added.
public async Task<Employee> GetSignInActivity(string name)
{
var graphClient = CreateGraphClient();
var result = await graphClient.Users.GetAsync(cfg =>
{
cfg.QueryParameters.Filter = $"startswith(displayName,'{name}')";
cfg.QueryParameters.Select = new[] { "displayName", "signInActivity" };
});
// TODO: Map 'result' to Employee
return new Employee();
}
5.3 GetUser(string username)
Fetches a user by exact displayName, then enriches with signâin data.
public async Task<Employee> GetUser(string username)
{
var graphClient = CreateGraphClient();
// 1. Filter by displayName
var result = await graphClient.Users.GetAsync(cfg =>
{
cfg.QueryParameters.Filter = $"displayName eq '{username}'";
cfg.QueryParameters.Select = new[] { "id", "mail", "displayName", "signInActivity", "Department" };
});
// 2. Get the primary user object
var usr = await graphClient.Users[username].GetAsync();
// 3. Map to Employee
var emp = new Employee
{
FullName = usr.DisplayName,
Title = usr.JobTitle,
Department = usr.Department,
Email = usr.Mail,
EmployeeNumber = usr.EmployeeId,
PhoneNumber = usr.MobilePhone
};
// 4. Map signInActivity
if (result.Value.Any() && result.Value[0].SignInActivity != null)
{
var sa = result.Value[0].SignInActivity;
emp.LastSignInDateTime = sa.LastSignInDateTime?.DateTime;
emp.LastNonInteractiveSignInDateTime = sa.LastNonInteractiveSignInDateTime?.DateTime;
emp.Department = result.Value[0].Department ?? emp.Department;
}
return emp;
}
5.4 GetUserDetails(string email)
Combines AD info with local DB.
- Calls
GetUserADList(email) - Attempts to find a matching record in
_context.Employees - If found, patches
JobNumbervia_context.Jobs - Returns a final
Employee
public Employee GetUserDetails(string email)
{
var res = GetUserADList(email).Result;
var dbEmp = _context.Employees
.FirstOrDefault(e => e.DisplayName == res.FullName
|| e.WorkEmail == email);
var emp = new Employee();
if (dbEmp == null)
{
// ADâonly
emp = res;
}
else
{
// Augment with JDE job number
var job = _context.Jobs.FirstOrDefault(j => j.JobId == dbEmp.JobId);
emp.JobNumber = job?.JdeNumber;
emp.FullName = dbEmp.DisplayName;
emp.Email = res.Email;
emp.EmployeeNumber= dbEmp.JdeNumber;
emp.PhoneNumber = res.PhoneNumber;
emp.Title = res.Title;
emp.Department = res.Department;
}
return emp;
}
5.5 GetAllUserADList(string email)
Produces a list of active employees (SelectListItem) for UI dropdowns:
public List<SelectListItem> GetAllUserADList(string email)
{
return _context.Employees
.Where(e => e.Status != EmployeeStatus.Terminated)
.Select(e => new SelectListItem
{
Value = e.JdeNumber,
Text = $"{e.LastName}, {e.FirstName}"
})
.ToList();
}
6. Data Models
| Model | Key Properties |
|---|---|
| Employee (ViewModel) | Guid UserIdstring FullNamestring Titlestring Departmentstring Emailstring EmployeeNumberstring PhoneNumberDateTime? LastSignInDateTimeDateTime? LastNonInteractiveSignInDateTimestring JobNumber |
Note: The Employee class resides in IrbyImaging.ViewModels and is used to carry user data to the UI.
7. Error Handling & Return Types
-
Return Types:
- Asynchronous:
Task<Employee> - Synchronous:
Employee,List<SelectListItem>
- Asynchronous:
-
Exceptions:
- Graph API errors (
ODataError) are not explicitly caughtârecommend wrapping Graph calls intry/catchfor graceful failure. - Database lookups may throw if context is misconfigured; ensure migrations & schema are upâtoâdate.
- Graph API errors (
8. Thirdâparty Integrations
| Integration | Details |
|---|---|
| Microsoft Graph | Fetch user profiles, signâin activity, department, etc. |
| Azure Identity | ClientSecretCredentialâenables secure token acquisition |
| EntityFramework | CRUD operations on local SQL DB via IrbyContext |
9. Usage Examples
9.1 Registering the Service (Startup.cs)
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<IrbyContext>(options => /* ⊠*/);
services.AddScoped<AzureADRead>();
// ⊠other services
}
9.2 Inject & Use in an MVC Controller
public class UserController : Controller
{
private readonly AzureADRead _azureAdRead;
public UserController(AzureADRead azureAdRead)
{
_azureAdRead = azureAdRead;
}
public async Task<IActionResult> Profile(string email)
{
var employee = await _azureAdRead.GetUserADList(email);
return View(employee);
}
}
9.3 Razor View Snippet
@model Employee
<h2>đ€ @Model.FullName</h2>
<p>
<strong>Email:</strong> @Model.Email<br/>
<strong>Title:</strong> @Model.Title<br/>
<strong>Department:</strong> @Model.Department<br/>
<strong>Last SignâIn:</strong> @Model.LastSignInDateTime?.ToString("g")
</p>
10. Conclusion â
The AzureADRead service encapsulates all interactions with Azure AD and Microsoft Graph, provides a unified Employee view model, and blends AD data with local business rules. By centralizing this logic:
- đ Controllers stay lean and focused on HTTP concerns
- đ Reusability is maximized across pages & features
- đ Maintainability improves through a single source of truth for AD reads
Future enhancements may include caching responses, implementing paging for large user sets, and robust error handling (e.g., retry policies).
Happy coding! đ