• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Wednesday, July 19, 2017

Implementing basic authentication in ASP NET Web API

 Abhishek Tomer     July 19, 2017     Asp.Net, Asp.Net MVC, Web API     1 comment   

Overview:
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
  1. Create a database that have user related information like UserName and Password in my case i have used following tables show below as:
  2. Create a new Blank Project named as BacisAuthentication
  3. Add an empty Asp.net Web API Project with No Authentication Mode selected from templates named as Demo.API
  4. Add a console application for data named as Demo.Data that contains two folders like Repository and Entity.
  5. Install the Entity Framework in both project. 
  6. Add the EDMX files in Entity folder and select both table.

    Implementing basic authentication in ASP NET Web API
    Entities in EntityFramework(EDMX) Diagram

  7. Create UserRepository Class and Add the following code as
  8. 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;
            }
        }
    }
    
  9. Create EmployeeRepository for get the employee related data from database as:
  10. 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 List GetAll()
            {
                return _Context.Employees.ToList();
            }
            public Employee GetByID(int ID)
            {
                return _Context.Employees.Find(ID);
            }
        }
    }
    
  11. Adding the reference of Demo.Data project to Demo.API project.
  12. 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.
  13. 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);
                    }
                }
            }
        }
    }
    
  14. 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
  15. 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);
            }      
        }
    }
    
  16. Now test the api by passing the user name and password in encoded formate in header with basic.
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=
Implementing basic authentication in ASP NET Web API
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 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

1 comment:

  1. rmouniakOctober 10, 2018 at 9:31 AM

    I like your blog, I read this blog please update more content on hacking,
    Nice post,and good information Thanks for sharing
    further check it once at .NET Online Course

    ReplyDelete
    Replies
      Reply
Add comment
Load more...

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • Comparison Between HttpModule and HttpContext
    Hi friends! Today we are going to list some of the differences between HttpModule and HttpContext. Many of my developer friends are confus...
  • How to Reverse a String in C#
    In this article, I am going to discuss How to Reverse a String in C# with and without using built-in Methods. Please read our previous art...
  • Reverse Number Program in C# with Examples
    In this article, I am going to discuss the Reverse Number Program in C# with some examples. Please read our previous article where we discu...
  • Armstrong Number Program in C# with Examples
    In this article, I am going to discuss the Armstrong Number Program in C# with some examples. Please read our previous article before proc...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...
  • Decimal to Binary Conversion in C# with Examples
    In this article, I am going to discuss the Decimal to Binary Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape