Implement basic authentication in web api c#

First, create an empty web API project . Then follow the below steps:

Here I want to validate the user if the user exists then display the employee details based on username.

1. Create a User model class and Employee model.

User Model Class
Employee Model Class
public class User
    {
        public int ID { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
    }
  
 public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string Dept { get; set; }
        public int Salary { get; set; }
    }

 

2. Creating a class that returns the list of employees and users.

User List
Employee List
public class UsersBL
    {
        public List GetUsers()
        {          
            List userList = new List();
            userList.Add(new User()
            {
                ID = 101,
                UserName = "MaleUser",
                Password = "123456"
            });
            userList.Add(new User()
            {
                ID = 101,
                UserName = "FemaleUser",
                Password = "abcdef"
            });
            return userList;
        }
    }
  
 public class EmployeeBL
    {
        public List GetEmployees()
        {
            List empList = new List();
            for (int i = 0; i < 10; i++)
            {
                if (i > 5)
                {
                    empList.Add(new Employee()
                    {
                        ID = i,
                        Name = "Name" + i,
                        Dept = "IT",
                        Salary = 1000 + i,
                        Gender = "Male"
                    });
                }
                else
                {
                    empList.Add(new Employee()
                    {
                        ID = i,
                        Name = "Name" + i,
                        Dept = "HR",
                        Salary = 1000 + i,
                        Gender = "Female"
                    });
                }
            }
            return empList;
        }
 
3. Creating UserValidate class to validate the user

       public class UserValidate
        {
            //This method is used to check the user credentials
            public static bool Login(string username, string password)
            {
                UsersBL userBL = new UsersBL();
                var UserLists = userBL.GetUsers();
                return UserLists.Any(user =>
                    user.UserName.Equals(username, StringComparison.OrdinalIgnoreCase)
                    && user.Password == password);
            }
        }

4. Creating BasicAuthenticationAttribute class to implement basic authentication

      public override void OnAuthorization(HttpActionContext actionContext)
        {
            //If the Authorization header is empty or null
            //then return Unauthorized
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request
                    .CreateResponse(HttpStatusCode.Unauthorized);

                // If the request was unauthorized, add the WWW-Authenticate header
                // to the response which indicates that it require basic authentication
                if (actionContext.Response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    //Code
                }
            }
            else
            {
                //Get the authentication token from the request header
                string authenticationToken = actionContext.Request.Headers
                    .Authorization.Parameter;

                //Decode the string
                string decodedAuthenticationToken = Encoding.UTF8.GetString(
                    Convert.FromBase64String(authenticationToken));

                //Convert the string into an string array
                string[] usernamePasswordArray = decodedAuthenticationToken.Split(':');

                //First element of the array is the username
                string username = usernamePasswordArray[0];

                //Second element of the array is the password
                string password = usernamePasswordArray[1];

                //call the login method to check the username and password
                if (UserValidate.Login(username, password))
                {
                    var identity = new GenericIdentity(username);

                    IPrincipal principal = new GenericPrincipal(identity, null);
                    Thread.CurrentPrincipal = principal;

                    if (HttpContext.Current != null)
                    {
                        HttpContext.Current.User = principal;
                    }
                }
                else
                {
                    actionContext.Response = actionContext.Request
                        .CreateResponse(HttpStatusCode.Unauthorized);
                }
            }
        }

5. Add the below code in webApiConfig.cs file

            config.Filters.Add(new BasicAuthenticationAttribute());

6. Finally, create a controller and add [BasicAuthentication] filter for which you want to authenticate

    [BasicAuthentication]
    public class DefaultController : ApiController
    {
 
        public HttpResponseMessage GetEmployees()
        {
            string username = Thread.CurrentPrincipal.Identity.Name;
            var EmpList = new EmployeeBL().GetEmployees();
            switch (username.ToLower())
            {
                case "maleuser":
                    return Request.CreateResponse(HttpStatusCode.OK,
                        EmpList.Where(e => e.Gender.ToLower() == "male").ToList());
                case "femaleuser":
                    return Request.CreateResponse(HttpStatusCode.OK,
                        EmpList.Where(e => e.Gender.ToLower() == "female").ToList());
                default:
                    return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }

    }

Popular posts from this blog

How to get the user details, user current level, next level, Rank in sql server

How to update the user level when ever user report any tweet in sql

Implement virtualisation in kendo drop down list using jquery ajax in mvc, aspx page