What is ASP.NET Web API?
ASP.NET Web API is a framework used to build HTTP services that reach a broad range of clients such as Browsers, Mobile applications, Desktop applications, IOTs, etc. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
ASP.NET Web API allows us different ways to implement security while exposing resources.
- Basic Authentication
- Token Based Authentication
- JWT Authentication etc.
Basic authentication a mechanism where end user authenticated through our provide service. An end user makes a request to the service for authentication with user name and password embedded in request header. Service receives the request and checks if the credentials are valid or not, and returns the response accordingly. Service responds with 401 error code i.e. unauthorized when the user input invalid credentials.
Pros of Basic Authentication:
It is very easy to implement, it is nearly supported by all modern browsers and has become an authentication standard in RESTful / Web APIs.
Cons of Basic Authentication:
Sending user credentials in plain text, sending user credentials inside request header, i.e. prone to hack. One have to send credentials each time a service is called. No session is maintained and a user cannot logout once logged in through basic authentication. It is very prone to CSRF (Cross Site Request Forgery).
Implementation of ASP.NET Web API using basic authentication
Step-1: Open VS 2017 >> File >> New Project >> ASP .NET Web Application
Choose application as Web API |
Step-2: Add the below classes inside the Models folder
(i) BasicAuthenticationAttribute.cs
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
else
{
// Gets header parameters
string authenticationString = actionContext.Request.Headers.Authorization.Parameter;
string originalString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString));
// Gets username and password
string username = originalString.Split(':')[0];
string password = originalString.Split(':')[1];
if (APISecurity.Validate(username, password))
{
Thread.CurrentPrincipal = new GenericPrincipal(
new GenericIdentity(username), null);
}
else
{
actionContext.Response = actionContext.Request
.CreateResponse(HttpStatusCode.Unauthorized);
}
}
base.OnAuthorization(actionContext);
}
}
public class APISecurity
{
public static bool Validate(string username, string password)
{
if (username.Equals("CoreProgramm", StringComparison.OrdinalIgnoreCase)
&& password == "Core@4327$")
{
return true;
}
else
{
return false;
}
}
}
>> The BasicAuthenticationAttribute is responsible to authenticate the API service when the end user fetch the api. Through APISecurity class we define our credentials when user fetch the service it must append the valid credentials otherwise the service output is invalid. >> The Attribute We can use in Action method or Controller.(iii) Employee.cs : Add the employee class that return employee information.
namespace BasicAuthenticationWebAPI.Models
{
public class Employee
{
public int EmpNo { get; set; }
public string EmpName { get; set; }
public int Salary { get; set; }
public string DeptName { get; set; }
}
public class Employees : List<Employee>
{
public Employees()
{
Add(new Employee() { EmpNo = 101, EmpName = "John",
Salary = 12000, DeptName = "IT" });
Add(new Employee() { EmpNo = 102, EmpName = "Tom",
Salary = 22000, DeptName = "System" });
Add(new Employee() { EmpNo = 103, EmpName = "Smith",
Salary = 21000, DeptName = "Sales" });
Add(new Employee() { EmpNo = 104, EmpName = "Lora",
Salary = 32000, DeptName = "HRD" });
Add(new Employee() { EmpNo = 105, EmpName = "Jodie",
Salary = 42000, DeptName = "HRD" });
Add(new Employee() { EmpNo = 106, EmpName = "Wonda",
Salary = 12000, DeptName = "Admin" });
}
}
}
namespace BasicAuthenticationWebAPI.Controllers
{
[BasicAuthentication]
public class ValuesController : ApiController
{
[Route("api/employees")]
public HttpResponseMessage GetEmployees()
{
Employees emp = new Employees();
string username = Thread.CurrentPrincipal.Identity.Name;
if (username == "CoreProgramm")
{
return Request.CreateResponse(HttpStatusCode.OK, emp);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest,
"Unauthorized User");
}
}
}
}
You can see 401 Unauthorized access is show due to we haven't declare authentication. |
Now add the UserName and password what are we use APISecurity.cs and see the output.
You can see status as 200 and result print as expected. |
/> The Source Code is available in Github.com/CoreProgramm/
Summary
Post a Comment