Can't delete cookie with AngularJS's $cookies

前端 未结 3 1611
遇见更好的自我
遇见更好的自我 2021-01-17 09:28

My web app is made so that when a user logs in the server adds a Set-Cookie header to the response, like this:

Set-Cookie:JSESSIONID=1; Path=/myApp/; Secure

相关标签:
3条回答
  • 2021-01-17 09:53

    I suppose you should check the responses from server - maybe they include a 'set cookie' header field that sets the cookie's value.

    Here is a Plunker example that illustrates how you can add/change/delete/watch for cookie's value (but without server-side responses that can change cookie values).

    But generally, $cookies object is kind of 'proxy object' that is two-way tracked by AngularJS ngCookies module and from one side change its fields when browser's cookies are changed (so you can $watch for changes) but also changes are reflected to browser's real cookies, so you can change this object.

    So the only reason why cookies cannot be deleted is that you delete them on browser, and server sets the cookie again and after reloading page it is still there.

    0 讨论(0)
  • 2021-01-17 09:58

    Be aware of the cookie domain of the cookie you want to delete. If you're working with multiple subdomains (i.e. one for static resources, another for the api) your problem could be that you're trying to delete a cookie for the wrong domain.

    Have a look at your cookies with your browser's developer tool of choice. Whatever domain is set for the cookie you want to delete that you're having problems with, specify it in the options parameter to the remove method.

    $cookies.remove('JSESSIONID', {domain: 'domain.tld'});
    

    SECURITY TIP: Deleting the session ID via Javascript doesn't delete the session on the server. If your session IDs leak you could suffer from session fixation. It would be better to delete the cookie via calling a logout endpoint in your API which would clear the session completely on the server so that it can't be re-used.

    0 讨论(0)
  • 2021-01-17 10:07

    The answer that you gave in the update seems to be correct: Angular $cookieStore can only work on cookies whose path value is the same as the current path.

    The way to trick it is to use the solution given by ajspera on this issue:

    <head>
      <base href="/">
    </head>
    

    Simply add <base href="/"> to your head element of the HTML, and at that point it works.

    The alternative solution is to set the path of the cookie using the server that sent it. In Node.js Express that looks like

    res.cookie('specialCookie', 'special!', {path: '/myApp'});
    

    Note that for me it seems like $cookieStore strips out the trailing slash, so you may need to try it both ways.

    0 讨论(0)
提交回复
热议问题