Javascript Angularjs 中的记住我的功能和令牌
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26645271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remember me functionality and Token in Angularjs
提问by GeekOnGadgets
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.
我在这里寻找更好的方法来解决我的问题。我的登录表单上有记住我的功能。用户点击记住我框,我的 API 向我发送令牌。
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.
- 创建一个 Cookie 并将令牌存储在那里。
- 创建本地存储。
Please give me any advice which might help me.
请给我任何可能对我有帮助的建议。
采纳答案by willjleong
I would use document.cookie with a factory code like this:
我会将 document.cookie 与这样的工厂代码一起使用:
Creates a cookie (for example this one expires in a year):
创建一个 cookie(例如这个在一年后过期):
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:
这个工厂删除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 缓存密钥:
$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
并且在用户登录时始终检查cookie是否存在,否则使用标准登录并将其保存到他们的cookie中。如果未启用记住我,请忘记 document.cookie
回答by Umair Ahmed
Use ngCookies:The ngCookies module provides a convenient wrapper for reading and writing browser cookies.
使用 ngCookies:ngCookies 模块为读取和写入浏览器 cookie 提供了一个方便的包装器。
First you install ngCookies in your app using bower bower install [email protected]or manully.
首先,您使用 bowerbower install [email protected]或manully 在您的应用程序中安装 ngCookies 。
then inject ngCookiesin your app like
angular.module('app', ['ngCookies']);
然后注入ngCookies你的应用程序
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');
}]);
回答by adentum
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 sessionStorageis 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:
如果您使用令牌身份验证/ Restful API,那么首选方法是使用localStorage. 但是,除非用户选择“记住我”,否则使用这种方法时,他们将需要再次登录到他们打开的每个浏览器选项卡。因为保存的每个项目sessionStorage仅可用于单个选项卡。我创建了一个库来简化此操作并在所有打开的选项卡之间同步会话数据。用户体验类似于 cookie 身份验证提供的体验。有了这个,您可以执行以下操作:
if (rememberMe)
storageManager.savePermanentData('data', 'key');
else
storageManager.saveSyncedSessionData('data', 'key');
And you retrieve data by var myData = storageManager.getData('key');
然后你检索数据 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
你可以从这个链接下载这个库:http: //www.ebenmonney.com/blog/how-to-implement-remember-me-functionality-using-token-based-authentication-and-localstorage-in-a-web -应用
回答by Saniya syed qureshi
(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>

