Remember me functionality and Token in Angularjs
Solution 1
I would use document.cookie with a factory code like this:
Creates a cookie (for example this one expires in a year):
app.factory('$remember', function() {
return function(name, values) {
var cookie = name + '=';
cookie += values + ';';
var date = new Date();
date.setDate(date.getDate() + 365);
cookie += 'expires=' + date.toString() + ';';
document.cookie = cookie;
}
});
This factory removes the cookie:
app.factory('$forget', function() {
return function(name) {
var cookie = name + '=;';
cookie += 'expires=' + (new Date()).toString() + ';';
document.cookie = cookie;
}
});
Then whenever a user successfully logs in cache the key using $remember:
$remember('my_cookie_name', response.user._id);
And always check if the cookie is there when logging in the user else use a a standard login and save it to their cookies. If the remember me is not enabled, forget the document.cookie
Solution 2
Use ngCookies: The ngCookies module provides a convenient wrapper for reading and writing browser cookies.
First you install ngCookies in your app using bower bower install [email protected]
or manully.
then inject ngCookies
in your app like
angular.module('app', ['ngCookies']);
then simply use like
angular.module('App', ['ngCookies'])
.controller('demo', ['$cookies', function($cookies) {
// Setting a cookie
$cookies.put('cookieName', 'object');
// Retrieving a cookie
var sample= $cookies.get('cookieName');
// Remove a cookie
$cookies.remove('cookieName');
}]);
GeekOnGadgets
Updated on July 09, 2022Comments
-
GeekOnGadgets almost 2 years
I am looking for a better approach to my problem here. I have a remember me functionality on my login form. Ones the user click on remember me box, My API sends me Token.
My question is what is the best way to store this token and authenticate user again when they are back to my site?
What I thought,
- Create a Cookie and store token there.
- Create a local Storage.
Please give me any advice which might help me.
-
GeekOnGadgets over 9 yearsnice answer :) I will try and let you know.
-
GeekOnGadgets over 9 yearsCan you please explain more on how to check if my cookie is set? Currently I am using a Boolean flag but does not work. Any idea?
-
ashishkumar148 over 9 yearscookie is not removing from browser even after it is expired.
-
Umair Ahmed about 8 years@willjleong how we check cookie ? and then apply condition according to cookie. can you further explain .
-
Mustafa almost 8 yearsThis should be used as an accepted answer as it is not a good practice to use DOM objects inside angular code.