In this post I am going to explain to how to implement basic authentication using custom authentication filter. Here am not using any membership technique like asp.net identity. Here I have created our own database that contains UserMaster table and Employee table.
There are following steps to achieve our goal
- Create a database that have user related information like UserName and Password in my case i have used following tables show below as:
- Create a new Blank Project named as BacisAuthentication
- Add an empty Asp.net Web API Project with No Authentication Mode selected from templates named as Demo.API
- Add a console application for data named as Demo.Data that contains two folders like Repository and Entity.
- Install the Entity Framework in both project.
- Add the EDMX files in Entity folder and select both table.
Entities in EntityFramework(EDMX) Diagram
- Create UserRepository Class and Add the following code as
- Create EmployeeRepository for get the employee related data from database as:
- Adding the reference of Demo.Data project to Demo.API project.
- Create a Customer Filter for user authentication. here we need to create our custom authentication filter by creating a class BacisAthentication in model and implement the AuthorizationFilterAttribute. Complete code is given below.
- Now need to create a employee controller in controller folder and use the BasicAuthentication filter on each employee service. Means that if user is authenticated then we provide the service otherwise not. The following controller code is
- Now test the api by passing the user name and password in encoded formate in header with basic.
using Demo.Data.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Demo.Data.Repository { public class UserRepository { //Initialize the db context private DemoContext _Context; public UserRepository() { //Creating the db context object _Context = new DemoContext(); } //Validate User by user name and passord public bool ValidateUser(string userName,string Password) { var result= _Context.UserMasters.SingleOrDefault(x => x.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase) && x.Password==Password); return result!=null?true:false; } } }
using Demo.Data.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Demo.Data.Repository { public class EmployeeRepository { //Initialize the db context private DemoContext _Context; public EmployeeRepository() { //Creating the db context object _Context = new DemoContext(); } public ListGetAll() { return _Context.Employees.ToList(); } public Employee GetByID(int ID) { return _Context.Employees.Find(ID); } } }
using Demo.Data.Repository; using System; using System.Net; using System.Net.Http; using System.Security.Principal; using System.Text; using System.Threading; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace Demo.API.Models { public class BacisAthentication:AuthorizationFilterAttribute { public override void OnAuthorization(HttpActionContext actionContext) { //Check client passed any value in header or not if (actionContext.Request.Headers.Authorization == null) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); } else { //Get the Hear values string authenticationToken = actionContext.Request.Headers.Authorization.Parameter; //Decoded the authenticationToken values becouse client passed the user namd and password in encoded form string decodedAuthenticationToken =Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken)); //Split the user name and password by : because client passed the user name and password as"userNameValue:Passwordvalue" string[] usernamePasswordArray = decodedAuthenticationToken.Split(':'); string username = usernamePasswordArray[0]; string password = usernamePasswordArray[1]; UserRepository _userRepository = new UserRepository(); //validate from the database for this user name or passrod. if (_userRepository.ValidateUser(username, password)) { Thread.CurrentPrincipal = new GenericPrincipal(newGenericIdentity(username), null); } else { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); } } } } }
using Demo.API.Models; using Demo.Data.Entity; using Demo.Data.Repository; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace Demo.API.Controllers { public class EmployeeController : ApiController { private EmployeeRepository emp = new EmployeeRepository(); // GET api/Employee [BacisAthentication] public IEnumerable<Employee> Get() { return emp.GetAll(); } // GET api/Employee/5 [BacisAthentication] public Employee Get(int id) { return emp.GetByID(id); } } }
You can encode the username:password here
https://www.base64encode.org/
before encode
userName1:Password1
after encoded
dXNlcjE6cGFzd29yZDE=
In Header You need to select or write Authorization in key and in value section pass encoded value with basic example : basicdXNlcjE6cGFzd29yZDE=
Example for Testing API |
Summary:
So, Guys This concludes the concept of achieving authentication in ASP NET Web API.
I Hope this post will be helpful to understand the concept of Asp.Net Web API.
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
I like your blog, I read this blog please update more content on hacking,
ReplyDeleteNice post,and good information Thanks for sharing
further check it once at .NET Online Course