0% found this document useful (0 votes)
33 views4 pages

ASP.NET Core Web API with Azure AD Auth

This document outlines the steps to create an ASP.NET Core Web API application with Azure Active Directory authentication in Visual Studio 2019. Key steps include: 1. Installing the Azure AD authentication NuGet package. 2. Configuring the API to use client ID and tenant ID from app registrations in the Azure Active Directory. 3. Registering authentication and CORS services in the Startup class to enable authentication and allow requests from Angular application. 4. Creating sample Employee and EmployeesController classes to return test data from API upon authenticated request.

Uploaded by

Digil
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)
33 views4 pages

ASP.NET Core Web API with Azure AD Auth

This document outlines the steps to create an ASP.NET Core Web API application with Azure Active Directory authentication in Visual Studio 2019. Key steps include: 1. Installing the Azure AD authentication NuGet package. 2. Configuring the API to use client ID and tenant ID from app registrations in the Azure Active Directory. 3. Registering authentication and CORS services in the Startup class to enable authentication and allow requests from Angular application. 4. Creating sample Employee and EmployeesController classes to return test data from API upon authenticated request.

Uploaded by

Digil
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

Create ASP.

NET Core Web API in Visual Studio 2019


We can create [Link] Core Web API application using default API template in
Visual Studio.

We must install “[Link]” library using


NuGet. This is used for AD authentication.

We have already created two app registrations in Azure active directory. We can
use the client id and tenant id for API here in appsettings as given below.

[Link]

1. {
2. "Logging": {
3. "LogLevel": {
4. "Default": "Information",
5. "Microsoft": "Warning",
6. "[Link]": "Information"
7. }
8. },
9. "AllowedHosts": "*",
10. "AzureActiveDirectory": {
11. "Instance": "[Link]
12. "Domain": "<your domain>.[Link]",
13. "TenantId": "adbbbd82-76e5-4952-8531-3cc59f3c1fdd",
14. "ClientId": "api://e283d8fb-22ad-4e2c-9541-
14f6f118a08f"
15. }
16. }

We can register authentication service inside the ConfigureServices method in


Startup class. Also add CORS service as well.

[Link]

1. using [Link];
2. using [Link];
3. using [Link];
4. using [Link];
5. using [Link];
6. using [Link];
7. using [Link];
8. using System;
9.
10. namespace AzureADAPI
11. {
12. public class Startup
13. {
14. public Startup(IConfiguration configuration)
15. {
16. Configuration = configuration;
17. }
18.
19. public IConfiguration Configuration { get; }
20.
21. // This method gets called by the runtime. Use th
is method to add services to the container.
22. public void ConfigureServices(IServiceCollection
services)
23. {
24. [Link]();
25.
26. [Link]([Link]
arerAuthenticationScheme).AddAzureADBearer(options => Configur
[Link]("AzureActiveDirectory", options));
27.
28. string corsDomains = "[Link]

29. string[] domains = [Link](",".ToCh


arArray(), [Link]);
30.
31. [Link](o => [Link]("AppCORSPol
icy", builder =>
32. {
33. [Link]()
34. .AllowAnyMethod()
35. .AllowAnyHeader()
36. .AllowCredentials()
37. .WithOrigins(domains);
38. }));
39.
40. }
41.
42. // This method gets called by the runtime. Use th
is method to configure the HTTP request pipeline.
43. public void Configure(IApplicationBuilder app, IW
ebHostEnvironment env)
44. {
45. if ([Link]())
46. {
47. [Link]();
48. }
49.
50. [Link]("AppCORSPolicy");
51.
52. [Link]();
53.
54. [Link]();
55. [Link]();
56.
57. [Link](endpoints =>
58. {
59. [Link]();
60. });
61. }
62. }
63. }

Create an Employee class. This will be used in our Employees controller class to
return some dummy data to Angular application later.

[Link]

1. namespace AzureADAPI
2. {
3. public class Employee
4. {
5. public int Id { get; set; }
6. public string Name { get; set; }
7. public string Company { get; set; }
8. public string City { get; set; }
9. }
10. }

Create Employee controller with single Get method. This method will be called
from Angular application to test AD authentication.

[Link]

1. using [Link];
2. using [Link];
3. using [Link];
4.
5. // For more information on enabling Web API for empty projects
, visit [Link]
6.
7. namespace [Link]
8. {
9. [Authorize]
10. [Route("api/[controller]")]
11. public class EmployeesController : Controller
12. {
13. [HttpGet]
14. public IEnumerable<Employee> Get()
15. {
16. List<Employee> employees = new List<Employee>

17. {
18. new Employee { Id = 1, Name = "Sarathlal
Saseendran", Company = "Orion Business Innovations", City = "K
ochi" },
19. new Employee { Id = 2, Name = "Anil Soman
", Company = "Cognizant", City = "Bangalare" }
20. };
21. return employees;
22. }
23. }
24. }

Please note, we have decorated above controller with [Authorize] decorator.

We have completed the API application enabled with AD authentication. We can


create Angular application from scratch and add all the components and
services.

Common questions

Powered by AI

The 'Authorize' attribute in the EmployeesController class ensures that only authenticated users can access the controller's methods. This attribute is integral to the Azure AD authentication scheme by enforcing the security policies set forth by the Azure Active Directory. When Azure AD is used, it verifies user credentials and ensures that only users who have been authenticated against the prescribed identity provider (Azure AD in this case) can utilize the controller's endpoints, such as the method for retrieving employee data .

The appsettings.json file is structured to include an 'AzureActiveDirectory' section with keys such as 'Instance', 'Domain', 'TenantId', and 'ClientId'. These keys provide necessary configurations for AD authentication, specifying the Azure AD instance to connect to, the application domain, and identifiers used to associate the API with Azure AD. Proper configuration in appsettings.json is crucial because it informs the ASP.NET Core application of how to connect to Azure AD for authentication purposes, ensuring the API can securely authenticate requests .

ASP.NET Core's dependency injection (DI) system simplifies the management of services like authentication and CORS by allowing them to be registered and injected into the application. In `ConfigureServices`, services such as `AddAuthentication` and `AddCors` can be registered, enabling ASP.NET Core to manage their lifecycle automatically. This design pattern promotes loose coupling and flexibility, as services can be easily switched or modified without affecting the application logic relying on them. Additionally, DI allows services to be configured globally, ensuring consistent behavior throughout the application .

The EmployeeController indirectly utilizes dependency injection and CORS through the application-wide configuration in startup.cs. While the controller itself does not explicitly contain DI or CORS code, it benefits from these through ASP.NET Core's pipeline. The DI system ensures authentication services are available to the controller via the `UseAuthentication` middleware. Similarly, the CORS configuration implemented in the `Configure` method using `UseCors` allows the controller to process requests based on the defined policies, ensuring only allowed clients can access the endpoints securely .

ASP.NET Core Web API controls cross-origin requests using CORS policies, enabling the application to define which domains can make requests to the API. By calling `AddCors` in the `ConfigureServices` method, developers can set rules through a policy such as `AllowAnyOrigin()`, `AllowAnyMethod()`, and specific allowed origins with `.WithOrigins(domains)`. This configuration ensures that only the specified domains can interact with the API, mitigating risks associated with cross-origin attacks while maintaining flexibility for legitimate use cases .

To enable an Angular application to communicate with an ASP.NET Core Web API secured by Azure AD, key changes include configuring the Angular's HTTP client to use bearer tokens acquired from Azure AD. This involves using Microsoft’s ADAL (Active Directory Authentication Library) or MSAL (Microsoft Authentication Library) to manage authentication, ensure tokens are properly acquired and included in request headers of HTTP client calls to the API. Additionally, configuring CORS in ASP.NET to allow requests from the Angular app’s origin ensures that the server recognizes and processes requests properly .

Using Azure Active Directory (AD) authentication enhances security by providing a robust method for managing and validating user identities. It allows the API to leverage existing corporate identities in Azure for authentication, reduce the need for separate identity management, and ensures secure access through efficiently managed tokens. The inclusion of authentication services using `Microsoft.AspNetCore.Authentication.AzureAD.UI` and configuration settings in `appsettings.json` ensure that only authenticated users can access the API, helping prevent unauthorized access .

When defining CORS policies for an ASP.NET Core Web API, developers must consider which domains should be allowed to interact with the API, which HTTP methods and headers should be permitted, and whether credentials should be included. Policies are added using methods like `AllowAnyOrigin()`, `AllowAnyMethod()`, and `WithOrigins(domains)`. It's crucial to strike a balance between providing necessary access and ensuring that the API is not exposed to security vulnerabilities through overly permissive CORS policies .

In the startup.cs file, middleware components are configured within the `Configure` method to manage request flow. Components such as `UseCors` allow for defining cross-origin policies, `UseRouting` sets up request routing, `UseAuthentication` and `UseAuthorization` handle security authentication and authorization, while `UseEndpoints` configures the endpoints available in the application. These middleware elements work collectively to ensure requests are processed in an orderly manner - authenticated, authorized, and routed to the correct endpoint, thereby implementing security, routing, and protocol management within the ASP.NET Core environment .

Using model classes like 'Employee' in an ASP.NET Core API offers several advantages, including clear data structure definition, reusability, and maintainability. Model classes encapsulate data properties, allowing for consistent handling across various parts of the application and reducing code duplication. They facilitate data validation and transformation before it is transferred between the API and client applications. Model classes simplify development by creating a type-safe environment, ensuring compile-time checks and IntelliSense support in IDEs, which leads to fewer runtime errors .

You might also like