Step 1: Create an application.
Open Visual Studio 2019->Go to File manager ->project.
Create a new Asp.net Core Web Application project with the "Auth_Demo” name and click on the Create button.
Figure 4 Create an Asp.net Core web application
Step 2: Choose Template.
Select the Asp.Net Core Web API template and click on the Create button.
Figure 5 Select Asp.Net Core Web API Template
Step 3: Add Business Logic.
Right-click on solution->Add->New Folder
Create a new folder with the "Service" name.
Step 4: Add Service Method and Interface.
Right-click on service Folder->Add->class and name it “EmployeeService”
Right-click on service Folder->Add->New Item->Interface and name it “IEmployeeService”
IEmployeeService
namespaceAuth_Demo.Service
{
publicinterfaceIEmployeeService
{
boolLogin(string username, string password);
}
}
IEmployeeService
namespaceAuth_Demo.Service
{
publicclassEmployeeService:IEmployeeService
{
publicboolLogin(string username, string password)
{
returnusername.Equals("admin") &&password.Equals("1234");
}
}
}
Step 5: Add Authentication handler
Right-click on solution->Add->class “BasicAuthenticationHandler”
usingAuth_Demo.Service;
usingMicrosoft.AspNetCore.Authentication;
usingMicrosoft.Extensions.Logging;
usingMicrosoft.Extensions.Options;
using System;
usingSystem.Linq;
usingSystem.Net.Http.Headers;
usingSystem.Security.Claims;
usingSystem.Text;
usingSystem.Text.Encodings.Web;
usingSystem.Threading.Tasks;
namespaceAuth_Demo
{
publicclassBasicAuthenticationHandler :AuthenticationHandler
{
#region Property
readonlyIEmployeeService _employeeService;
#endregion
#region Constructor
publicBasicAuthenticationHandler(IEmployeeServiceemployeeService,
IOptionsMonitor options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock)
: base(options, logger, encoder, clock)
{
_employeeService = employeeService;
}
#endregion
protectedoverrideasync TaskHandleAuthenticateAsync()
{
string username = null;
try
{
varauthHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
var credentials = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Parameter)).Split(':');
username = credentials.FirstOrDefault();
var password = credentials.LastOrDefault();
if(!_employeeService.Login(username, password))
thrownewArgumentException("Invalid credentials");
}
catch (Exception ex)
{
returnAuthenticateResult.Fail($"Authentication failed: {ex.Message}");
}
var claims = new[] {
newClaim(ClaimTypes.Name, username)
};
var identity = newClaimsIdentity(claims, Scheme.Name);
var principal = newClaimsPrincipal(identity);
var ticket = newAuthenticationTicket(principal, Scheme.Name);
returnAuthenticateResult.Success(ticket);
}
}
}
Step 6: Add Employee Controller and Employee Model.
EmployeeModel
namespaceAuth_Demo
{
publicclassEmployeeModel
{
publicint Id { get; set; }
publicstring Name { get; set; }
}
}
Employee Controller
usingMicrosoft.AspNetCore.Authorization;
usingMicrosoft.AspNetCore.Mvc;
usingMicrosoft.Extensions.Logging;
usingSystem.Collections.Generic;
namespaceAuth_Demo.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
publicclassEmployeeController :ControllerBase
{
privatereadonlyILogger _logger;
publicEmployeeController(ILogger logger)
{
_logger = logger;
}
[HttpGet]
publicIEnumerableGet()
{
Listemp = new List
{
newEmployeeModel{Id=1,Name="Dhoni" },
newEmployeeModel{Id=2,Name="Virat" },
newEmployeeModel{Id=3,Name="Rohit" },
newEmployeeModel{Id=4,Name="Jasprit" },
newEmployeeModel{Id=5,Name="Chahal" }
};
return emp;
}
}
}
Step 7: Configure the Startup file.
Add configuration in Configure service method.
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", newOpenApiInfo { Title = "Test_Demo", Version = "v1" });
c.AddSecurityDefinition("basic", newOpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "basic",
In = ParameterLocation.Header,
Description = "Authentication"
});
c.AddSecurityRequirement(newOpenApiSecurityRequirement
{
{
newOpenApiSecurityScheme
{
Reference = newOpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "basic"
}
},
newstring[] {}
}
});
});
services.AddAuthentication("BasicAuthentication")
.AddScheme("BasicAuthentication", null);
services.AddTransient();
Step 8: Build and Run project.
Figure 8 Output