Search This Blog

Saturday, 27 October 2018

Token based Authentication in Web Api


In this demo, I will demonstrate how to perform token-based authentication using web api?

Steps…

      1.      Authenticate token from database or Web.config file.
2.      Authentication token already shared to user or client.
3.      User or Client need to pass same token to Authentication Header in subsequent request for access the resources.

Let’s Start…

Step 1: - Open Visual Studio 2015 => Goto File Menu => New => Project...

Step 2: - In the Installed Templates list, select Visual C# => Web

Step 3: - Select ASP.Net Web Application (.Net Framework) from the Web list => Type WebApiTokenAuthentication in the Name box and click OK

Step 4: - Select Empty template from ASP.NET Templates List and Checked Web API check box under Add folders and core references for:





























Step 5: - Open Solution Explorer => Right Click on the Controllers folder => Click Add => Click Controller… => Select Web API 2 Controller – Empty => Click Add button


























Step 6: - Type Demo in Controller name box => Click Add button

Step 7: - Open Solution Explorer => Right Click on the Models folder => Click Add => Click New Items… => In the Installed Templates list, select Visual C# from left pane => Select Code from left pane=> Select Class from middle pane => Type CustomeAuthorizeAttribute.cs in the Name box => Click Add Button

Step 8: - Copy Past following Code into CustomeAuthorizeAttribute.cs

using System.Configuration;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace WebApiTokenAuthentication.Models
{
    public class CustomeAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (SkipAuthorization(actionContext))
            {
                return;
            }
            if (actionContext.Request.Headers.Authorization == null)
            {
                this.HandleUnauthorizedRequest(actionContext);
            }
            else
            {
                bool flag = isTokenAuthorized(actionContext.Request.Headers.Authorization.Scheme);
                if (!flag)
                {
                    this.HandleUnauthorizedRequest(actionContext);
                }
            }
        }

        private static bool SkipAuthorization(HttpActionContext actionContext)
        {
            return actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any<AllowAnonymousAttribute>() || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any<AllowAnonymousAttribute>();
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            base.HandleUnauthorizedRequest(actionContext);
        }

        private bool isTokenAuthorized(string token)
        {
            string config_Token = ConfigurationManager.AppSettings["Token"].ToString();
            if (!config_Token.Equals(token))
            {
                return false;
            }
            return true;
        }
    }
}

Step 9: - Copy Past following Code into DemoController

Note:- Created Custom Authorize Attribute in the Step 7, 8 using here above DemoController.

using System.Net.Http;
using System.Web.Http;
using WebApiTokenAuthentication.Models;

namespace WebApiTokenAuthentication.Controllers
{
    [CustomeAuthorize]
    public class DemoController : ApiController
    {
        [HttpGet]
        [AllowAnonymous]
        public HttpResponseMessage Login()
        {
            return Request.CreateResponse("Login with your authentication token.");
        }

        [HttpPost]
        public HttpResponseMessage Index1()
        {
            // Add Your Code Here...
            return Request.CreateResponse("You are authorized. Index1.");
        }

        [HttpPost]
        public HttpResponseMessage Index2()
        {
            // Add Your Code Here...
            return Request.CreateResponse("You are authorized. Index2.");
        }
    }
}

Step 9: - Open Solution Explorer => Open App_Start folder => Double click on WebApiConfig.cs to open

Existing line

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

Change to

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

Step 10: - Open Solution Explorer => Double click on Web.config to open => Copy Page following code to under <appSettings> section.

<add key="Token" value="1129D923-FF8F-4BAA-9AF8-D43A79EA0A70"/>

Step 11: - Run Project

ALL Done

Step 12: - Launch Postman

Step 13: - Copy Past following URL in URI and Hit Send button


Note: - Response received “Login with your authentication token.”





















Step 14: - Copy Past following URL in URI


Note: - Past authentication token value i.e. shared to you in the authentication headers





















Step 15: - Hit Send button, in response authorized message received.
  





















Step 16: - This time don’t send the authentication token value i.e. shared to you in the authentication headers and Hit Send button.

Note: - Response received “Authorization has been denied for this request.”




Cookies based Authentication in Web Api


In this demo, I will demonstrate how to perform cookies-based authentication using web api?

Steps…

       1.       When user login into system cookies will generate
2.       
Generated cookies send to user in response
3.       
User need to pass same cookies to Header in subsequent request for access the resources.

Let’s Start…

Step 1: - Open Visual Studio 2015 => Goto File Menu => New => Project...

Step 2: - In the Installed Templates list, select Visual C# => Web

Step 3: - Select ASP.Net Web Application(.Net Framework) from the Web list => Type WebApiCookieAuthentication in the Name box and click OK

Step 4: - Select Empty template from ASP.NET Templates List and Checked Web API check box under Add folders and core references for:





























Step 5: - Open Solution Explorer => Right Click on the Controllers folder => Click Add => Click Controller… => Select Web API 2 Controller – Empty => Click Add button



























Step 6: - Type Demo in Controller name box => Click Add button

Step 7: - Copy Past following Code into DemoController

using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Security;

namespace WebApiCookieAuthentication.Controllers
{
    [Authorize]
    public class DemoController : ApiController
    {
        [HttpGet]
        [AllowAnonymous]
        public HttpResponseMessage Login()
        {
            HttpContext.Current.Response.Cookies.Clear();

            FormsAuthentication.Initialize();

            FormsAuthentication.SetAuthCookie("WebApiDemoCookies", false);

            var str1 = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

            var str2 = FormsAuthentication.Decrypt(str1.Value);

            var str3 = ".ASPXAUTH=" + str1.Value.ToString();

            return Request.CreateResponse(str3);
        }

        [HttpPost]
        public HttpResponseMessage Index1()
        {
            // Add Your Code Here...
            return Request.CreateResponse("You are authorized. Index1.");
        }

        [HttpPost]
        public HttpResponseMessage Index2()
        {
                   // Add Your Code Here...
            return Request.CreateResponse("You are authorized. Index2.");
        }
    }
}

Step 8: - Open Solution Explorer => Open App_Start folder => Double click on WebApiConfig.cs to open

Existing line

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

Change to

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

Step 9: - Open Solution Explorer => Double click on Web.config to open => Copy Page following authentication section under <system.web> section.

    <authentication mode="Forms">
      <forms protection="All" timeout="20"  name=".ASPXAUTH" path="/" requireSSL="false"  slidingExpiration="true" cookieless="UseCookies" enableCrossAppRedirects="true"  domain="WebApiDemo" />
    </authentication>

Step 10: - Run Project

ALL Done

Step 11: - Launch Postman

Step 12: - Copy Past following URL in URI and Hit Send button


Note: - In response, we will get the cookies. Copy the Cookies value from response to use the same in subsequent request.






















Step 13: - Copy Past following URL in URI


Note: - Past Cookies value in Headers























Step 14: - Hit Send button, in response authorized message received.





















Step 15: - This time don’t send the cookies value in headers and Hit Send button.

Note: - Response received “Authorization has been denied for this request.”





Note: - Cookies base Authentication not secure use other technique like token, User Name & Password etc.