Sample API .Net Core
Sample API .Net Core
Sample API .Net Core
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.
appsettings.json
1. {
2. "Logging": {
3. "LogLevel": {
4. "Default": "Information",
5. "Microsoft": "Warning",
6. "Microsoft.Hosting.Lifetime": "Information"
7. }
8. },
9. "AllowedHosts": "*",
10. "AzureActiveDirectory": {
11. "Instance": "https://login.microsoftonline.com/",
12. "Domain": "<your domain>.onmicrosoft.com",
13. "TenantId": "adbbbd82-76e5-4952-8531-3cc59f3c1fdd",
14. "ClientId": "api://e283d8fb-22ad-4e2c-9541-
14f6f118a08f"
15. }
16. }
Staturp.cs
1. using Microsoft.AspNetCore.Authentication;
2. using Microsoft.AspNetCore.Authentication.AzureAD.UI;
3. using Microsoft.AspNetCore.Builder;
4. using Microsoft.AspNetCore.Hosting;
5. using Microsoft.Extensions.Configuration;
6. using Microsoft.Extensions.DependencyInjection;
7. using Microsoft.Extensions.Hosting;
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. services.AddControllers();
25.
26. services.AddAuthentication(AzureADDefaults.Be
arerAuthenticationScheme).AddAzureADBearer(options => Configur
ation.Bind("AzureActiveDirectory", options));
27.
28. string corsDomains = "http://localhost:4200";
Create an Employee class. This will be used in our Employees controller class to
return some dummy data to Angular application later.
Employee.cs
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.
EmployeeController.cs
1. using Microsoft.AspNetCore.Authorization;
2. using Microsoft.AspNetCore.Mvc;
3. using System.Collections.Generic;
4.
5. // For more information on enabling Web API for empty projects
, visit https://go.microsoft.com/fwlink/?LinkID=397860
6.
7. namespace AzureADAPI.Controllers
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. }