Extend the shelf life of cookies by utilizing AngularJS

I am currently implementing angularjs cookies in my project.

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

Despite being aware of the security risks, I am using $cookies to store user credentials. I aim for the user to log in once and have their session persist unless the cookies are manually cleared. However, I am facing an issue where the user has to log in again after closing the Chrome browser since the cookies are no longer available. I want the cookies to have a lasting presence without expiration.

Below is the relevant code segment 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 logic
                };

                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;
            }])

Is there a way to configure the cookies to never expire and persist even after the browser is closed?

Answer №1

After researching, it seems that setting a cookie to never expire is not truly possible. You can refer to this discussion on Stack Overflow for more information:

One workaround I found is to set the cookie expiration date to a future date. However, it is important to consider the 2038 bug that affects *nix systems (http://en.wikipedia.org/wiki/Year_2038_problem)

If you are using Angular 1.4+, you can utilize the $cookiesProvider options like this:

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

Although this information may be outdated, I hope it proves useful to someone in need.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deactivate the EventListener to continue playing the video

I have a JavaScript function that pauses a video when it reaches 5 seconds. <video id="home-hero-video" preload autoplay="autoplay" muted="muted"> <source src="videourl.mp4" type="video/mp4& ...

Retrieve a JSON response from within a schema housed in MongoDB

I have a document structure that looks like this: { "id": "someString", "servers": [ { "name": "ServerName", "bases": [ { "name": "Base 1", "status": true }, { "name": "Base 2", ...

I am currently in the process of verifying email addresses

I attempted to validate multiple email addresses from a txt file and then save the valid emails to another txt file using nodejs. Unfortunately, it did not work as expected. Despite successfully reading the file, all emails were deemed invalid, even though ...

Tips for effectively using the question mark as a separator in a webservice URL

In my nodejs / express project, I am attempting to create a webservice where I separate the URL from parameters using '?' and use '&' as parameter separators. When using this method, it works perfectly fine: app.get("/tableref/:event/ ...

Guide on merging an array in the state of a React Component

I've been working on developing a timesheet app. In the index.js file, I have set up the rendering of a table where the rows are populated from a children array that reads the state to ensure it stays updated. The function AddRow() is functioning prop ...

What is the best way to position the content on this page so that there is no horizontal scroll

Hey there! I'm currently working on a simple website using CSS flexbox, but I'm encountering an issue with my layout in About.vue. For some reason, this component is stretching out with a horizontal bar, even though it's only placed within t ...

"Troubleshooting: Mongoose uniqueness feature not functioning

I am encountering an issue with mongoose where 'unique:true' is not functioning as expected. Take a look at the schema I have formulated: var mongoose = require('mongoose'); var userSchema = mongoose.Schema({ username:{ type:St ...

Introducing unnecessary DOM elements when displaying flash messages

When a user saves in my Rails application, it triggers an Ajax request to save the post and then runs the update.js.erb file. This file contains some jQuery code: $('body').append('<div class="message">Saved</div>'); Due t ...

Angular 2 module transpilation services

In my angular 2 application, there is a module called common. Here is how the project structure looks like: main --app /common --config //.ts configs for modules --services //angular services --models --store //ngrx store /co ...

Disable the submit form in AngularJS when the start date and end date are not valid

I want to ensure that my form submission only occurs if the validation for Start date-End date passes. In my form setup, I have the following elements... <form name="scheduleForm" id="scheduleForm" class="form-vertical" novalidate> <input t ...

Having trouble sending data from AJAX to PHP

My goal is to implement a "load more" feature in my web app that automatically calls a PHP file to load additional products as soon as the page is fully loaded. In order to achieve this, I am using AJAX to call the PHP file: $(document).ready(function() { ...

Mastering Angular2: Leveraging TypeScript's Power to Unleash JavaScript ES6 Syntax with

I am having trouble implementing a translation feature using the ng2-translate pipe in my Angular2/Ionic2 app, which is entirely written in JavaScript ES6. However, I have encountered an issue during the setup phase. The code snippets I have found on the ...

I'm feeling a bit lost with this API call. Trying to figure out how to calculate the time difference between the

Currently, I am working on a project for one of my courses that requires making multiple API calls consecutively. Although I have successfully made the first call and set up the second one, I find myself puzzled by the specifics of what the API is requesti ...

The ConsoleCapture does not capture every console error for Sentry

Running into an issue capturing console errors with Sentry in a Next.js app. The problem arises from an error within a library that is inaccessible to us, specifically related to WebSocket "WebSocket is already in CLOSING or CLOSED state" This error is c ...

Automatically trigger a Bootstrap 5.2 modal when the page loads

Currently, I've been utilizing Bootstrap in conjunction with JQuery and have a specific code snippet that displays a Modal when a page is loaded. However, with the latest version 5.2 of Bootstrap, there is a push to move away from using JQuery (which ...

Once the getComponent is fully executed, move on to the getIndexRoute function

Within my react-router routes, I implemented plainRoutes in the following manner: getComponent (nextState, cb) { require.ensure([], (require) => { const CoreLayout = require('../layouts/CoreLayout/CoreLayout').default const u ...

Issue with Laravel: CKEditor text not loading HTML tags

Could you assist me with this? click here for the image description image description available here ...

Resetting input field based on callback function

In my simple script, I have two pages - script.php and function.php. The script.php page contains an input field with the ID #code, a link with the ID #submit, and a jQuery function. $('#submit').click(function () { $.ajax({ url: 'f ...

Showing text instantly upon clicking a radio button, in real-time

I'm working with a set of radio buttons that are linked to numbers ranging from 1 to 24. I need to show the selected number in another part of the page when a radio button is clicked. What would be the best way to achieve this? ...

I encountered an error while running a basic express app with ts-node-dev: Invalid argument: A non-string value was provided to `ts.resolveTypeReferenceDirective`

Recently, I started diving into Typescript and Express. Trying to set up a basic Express app using ts-node-dev, I encountered the following error: > ./node_modules/.bin/ts-node-dev src/index.ts 16:07:40 [I ...