22

I am developing an application in which users are SignUp or SignIn by External Identity Providers like AAD, Google, WS-Federated Authentication etc. Now I want to create cookies on a user machine to logged in until user SignOut. Give me some thought and guide me how I can overcome it. thanks in advance.

Malik Kashmiri
  • 5,741
  • 11
  • 44
  • 80

1 Answers1

41

Use Request.Cookies and Response.Cookies to handle your situation. once user coming back from third party authorization create cookie and store it in browser and once user Logout clear the cookie.

 string cookievalue ;
 if ( Request.Cookies["cookie"] != null )
 {
    cookievalue = Request.Cookies["cookie"].Value.ToString();
 }
 else
 {
    Response.Cookies["cookie"].Value = "cookie value";
 }

For removing cookie use following code

if (Request.Cookies["cookie"] != null)
{
    Response.Cookies["cookie"].Expires = DateTime.Now.AddDays(-1);   
}
Community
  • 1
  • 1
Nikhil.Patel
  • 959
  • 9
  • 17
  • 3
    Then how to use this code ? ControllerContext.HttpContext.Request.Cookies.Add(new HttpCookie("aa") { Expires = new DateTime().AddDays(5) , HttpOnly = true, Value = "val" }); – Bimal Das Jan 12 '18 at 12:20