[SalesForce] How to delete cookies in apex controller while clicking logout button on sites pages

I am using cookies to store user information on sites page using below logic.I am setting cookies when user logged in successfully on sites page

Cookie oktauserpwd = new Cookie('userpwd',userpwd,null,-1,false);
Cookie oktauserEmail= new Cookie('userEmail',userEmail,null,-1,false);
Cookie oktaappName= new Cookie('appName',appName,null,-1,false);
ApexPages.currentPage().setCookies(new Cookie[]{userpwd,userEmail,appName});

If user enters again login page in browsers url bar, he will directly redirected to home page depending on these cookies

  Cookie oktauserpwd = ApexPages.currentPage().getCookies().get('oktauserpwd');
  Cookie oktauserEmail= ApexPages.currentPage().getCookies().get('oktauserEmail');
  Cookie oktaappName= ApexPages.currentPage().getCookies().get('oktaappName');

  if(oktauserpwd !=null && oktauserEmail!=null && oktaappName!=null ){

   * here i will redirects to login page *        
  } 

No i am stuck to delete these cookies.When user clicks on logout button in home page he has to redirect to login page, but because of above if condition he is again redirected to home page.. technically he is not getting logged out , so i am thinking i have to delete these cookies on action method of the logout, so that it can redirect to login page instead of home page itself.

Is there any way to delete these cookies from apex coding.

Best Answer

I recommend you take a look at Cookie Class in the Apex Developer Guide. When a cookie is constructed it can be set such that it's only valid for the sessionId or for a limited amount of time (in seconds). This info can be retrieved using the getMaxAge() method making it unnecessary to keep track of any kind of session logout; something which may or may not happen. The cookie then doesn't need to be deleted, but is instead incremented by the constructor when it's name is retrieved by the controller on the next visit.

In your situation, when a user logs out, you can choose to set the MaxAge to 0 when a user logs out which effectively deletes the cookie.

Related Topic