Integrate Microsoft Azure Active Directory API in .NET
- Ensure that you have registered your application in Azure AD and have your client ID, tenant ID, and client secret ready. These will be necessary for authentication.
- Create a new ASP.NET Core project or use an existing one where you want to integrate Azure AD functionality.
dotnet new mvc --auth None
Configure Authentication Middleware
- Install the necessary NuGet packages for Azure AD integration. The primary package needed is Microsoft.Identity.Web.
dotnet add package Microsoft.Identity.Web
dotnet add package Microsoft.Identity.Web.MicrosoftGraph
- In your project, modify the Startup.cs or Program.cs (depending on .NET version) to use Azure AD for authentication.
// In Program.cs (for .NET 6.0 and above) or Startup.cs (for older versions)
using Microsoft.Identity.Web;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(config =>
{
Configuration.Bind("AzureAd", config);
});
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
Configure appsettings.json
- Add Azure AD settings to your appsettings.json configuration file to reference Azure tenant information.
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "yourtenant.onmicrosoft.com",
"TenantId": "your-tenant-id",
"ClientId": "your-client-id",
"ClientSecret": "your-client-secret",
"CallbackPath": "/signin-oidc"
}
}
Setup Azure AD Scopes and Permissions
- Navigate to the Azure portal and ensure your app registration has the required API permissions. Add any necessary Microsoft Graph permissions for your application.
API Permissions -> Add a permission -> Microsoft APIs -> Microsoft Graph -> Application/Delegated permissions
- Grant admin consent for the specific permissions your application needs to function properly.
Access Azure AD API in Your .NET Application
- Inject the GraphServiceClient into your controllers or services to access the Azure AD API.
using Microsoft.AspNetCore.Mvc;
using Microsoft.Graph;
public class HomeController : Controller
{
private readonly GraphServiceClient _graphServiceClient;
public HomeController(GraphServiceClient graphServiceClient)
{
_graphServiceClient = graphServiceClient;
}
public async Task<IActionResult> Index()
{
var user = await _graphServiceClient.Me.Request().GetAsync();
ViewBag.Username = user.DisplayName;
return View();
}
}
- Ensure that the necessary services are configured in your Startup.cs or Program.cs file to support dependency injection.
services.AddMicrosoftGraph(config =>
{
Configuration.Bind("AzureAd", config);
});
Run and Test
- Run your application, then ensure that users are redirected to Azure AD for authentication when accessing secure resources.
- After successful login, authenticated users should access any configured Azure AD resources seamlessly within your application environment.
This approach will help you effectively integrate Azure Active Directory API into your .NET application, providing authentication and authorization services leveraging Microsoft's cloud infrastructure. Customize the configuration and permissions to fit your particular application requirements.