Sunday, 7 October 2018

implement authentication on WEB API and consume with ajax Call


Below Steps to implement authentication on WEB API and consume with ajax Call

1.       Add a class in model folder  WebApiSecurity” and paste below code
                  using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebApiDemo.Models
{
   public class WebApiSecurity
    {
        public static bool VaidateUser(string username, string password)
        {
            // Check if it is valid credential 
            if (true)//CheckUserInDB(username, password)) 
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

2.       Create another class for basic authorization “BasicAuthenticationAttributeand paste below code
                 
              using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Filters;

namespace WebApiDemo.Models
{
   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 usrename = originalString.Split(':')[0];
                string password = originalString.Split(':')[1];

                // Validate username and password 
                if (!WebApiSecurity.VaidateUser(usrename, password))
                {
                    // returns unauthorized error 
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
            }

            base.OnAuthorization(actionContext);
        }
    }
}

3.       Add Basic Authentication Attribute [BasicAuthentication] on Web API Method like below code
                    using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiDemo.Models;
namespace WebApiDemo.Controllers
{
    public class EmployeeController : ApiController
    {
        List<EmployeeDetail> emp = new List<EmployeeDetail>()
        {
              new EmployeeDetail {Id="1",Name="Mohd Rizwan", City="Saharanpur" },
              new EmployeeDetail {Id="2",Name="Mohd Jabir", City="Delhi" },
              new EmployeeDetail {Id="3",Name="Mohd Waseem", City="Mumbai" }
        };
        [BasicAuthentication]
        [HttpGet]
        public IEnumerable<EmployeeDetail> GetAllEmplyees()
        {
return emp;           
        }
       
    }
}





Below steps to consume API with Ajax , Credential parameter like below code

function GetAllEmployees()
    {
                var username="userName";
                var password="user@123";
        var resturl = "http://localhost:44739/api/Employee/";
        resturl += "GetAllEmplyees";
        $.ajax({
            url: resturl,
            headers: {
                'accept': 'application/json;odata=verbose',
                'content-type': 'application/json;odata=verbose',
                                                                'Authorization' :'Basic ' + btoa(username + ':' + password)
            },
            async: false,
            success: function (data)
            {
              
                console.log(data)
            }, eror: function (data)
            {
                alert('error');
            }
        });
    }

No comments:

Post a Comment