Search This Blog

Saturday 27 October 2018

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.websection.

    <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.

2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Thanks a lot for sharing such a good source with all, i appreciate your efforts taken for the same. I found this worth sharing and must share this with all.




    Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery





    ReplyDelete