Make cookies never expire with angularjs

僤鯓⒐⒋嵵緔 提交于 2020-01-04 05:41:26

问题


I am using angularjs cookies.

https://docs.angularjs.org/api/ngCookies/service/$cookies

I am using $cookies to store username and password. I know that is bad practice but put that aside for the moment. I want the user to log in once and never need to do it again unless the cookies are cleared. However, the problem is that after the chrome browser is closed, the user has to log in again next time he visits the web page because the cookies are no longer present. I want the cookies to never expire.

Here is the relevant code written in a factory;

.factory('AuthenticationService',
        ['$base64', '$http', '$cookies', '$rootScope', '$timeout', 'configuration',
            function ($base64, $http, $cookies, $rootScope, $timeout, $configuration) {

                var service = {};

                service.Login = function (username, password, callback) {
                    //login code
                };

                service.SetCredentials = function (username, password) {
                    var authdata = $base64.encode(username + ':' + password);

                    $http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; 
                    $cookies.put('username', username);
                    $cookies.put('authdata', authdata);
                };

                return service;
            }])

How to make the cookies to never expire and remain there even after the browser is closed?


回答1:


from what I have read you can't really set it to never expire - see: https://stackoverflow.com/a/532638/669664

the best solution I came up with is to set it to a date in the future - but be conscious of the 2038 bug for *nix systems (http://en.wikipedia.org/wiki/Year_2038_problem)

using Angular 1.4+ - make use of the $cookiesProvider options:

            var expireDate = new Date();
            expireDate.setTime(2144232732000);
            if (thisIsAValue=== undefined) {
                $cookies.putObject("thisIsYourCookieObject", {
                    "foo": 1,
                    "bar": 1
                }, {'expires': expireDate});
            }

I know this is an old post - I hope this might help someone.



来源:https://stackoverflow.com/questions/34586494/make-cookies-never-expire-with-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!