Reputation: 959
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,
Please give me any advice which might help me.
Upvotes: 11
Views: 23475
Reputation: 3157
(function(angular) {
'use strict';
angular.module('app', ['ngCookies'])
.controller('mainController', ['$cookies', '$timeout', function($cookies, $timeout) {
var vm = this;
vm.message = '';
vm.getCookies = getCookies;
vm.setCookies = setCookies;
vm.clearCookies = clearCookies;
getCookies();
function getCookies()
{
vm.var1 = $cookies.get('var1');
vm.var2 = $cookies.get('var2');
}
function setCookies()
{
$cookies.put('var1', vm.var1);
$cookies.put('var2', vm.var2);
if (vm.var1 && vm.var2)
showMessage('Cookies set successefully!');
else
showMessage('Please enter some value.');
}
function clearCookies()
{
$cookies.remove('var1');
$cookies.remove('var2');
getCookies();
showMessage('Cookies cleared successefully!');
}
function showMessage(msg)
{
vm.message = msg;
$timeout(function() {
vm.message = '';
}, 2000);
}
}]);
})(window.angular);
body
{
padding: 10px;
}
<div ng-app="app" ng-controller="mainController as ctrl">
<div class="panel panel-default">
<div class="panel-heading">
<a href="https://docs.angularjs.org/api/ngCookies/service/$cookies">ngCookies</a> sample
</div>
<div class="panel-body">
Enter some value, press 'Set cookies', than refresh page. (Refresh button on right top corner)
<hr>
<form ng-submit="ctrl.setCookies()">
<div class="form-group">
<label for="var1">Cookies for VAR1</label>
<input type="text" class="form-control" id="var1" placeholder="value" ng-model="ctrl.var1">
</div>
<div class="form-group">
<label for="var2">Cookies for VAR1</label>
<input type="text" class="form-control" id="var2" placeholder="value" ng-model="ctrl.var2">
</div>
<button type="reset" class="btn btn-danger" ng-click="ctrl.clearCookies()">Clear</button>
<button type="submit" class="btn btn-primary">Set cookies</button>
</form>
</div>
</div>
<div class="alert alert-success" role="alert" ng-show="ctrl.message">
{{ctrl.message}}
</div>
</div>
Upvotes: 0
Reputation: 8787
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');
}]);
Upvotes: 15
Reputation: 1002
If you're using Token Authentication/ Restful API then the preferred way is to use the localStorage
. However using this approach unless the user selects to "Remember Me", they'll be required to login again to each browser tab they open. Because each item saved with sessionStorage
is only available to a single tab.
I created a library to simplify this and synchronize session data across all opened tabs. The user experience is similar to that offered by cookie authentication.
With this you do something like:
if (rememberMe)
storageManager.savePermanentData('data', 'key');
else
storageManager.saveSyncedSessionData('data', 'key');
And you retrieve data by var myData = storageManager.getData('key');
You can download this library from this link: http://www.ebenmonney.com/blog/how-to-implement-remember-me-functionality-using-token-based-authentication-and-localstorage-in-a-web-application
Upvotes: 0
Reputation: 153
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
Upvotes: 8