Angularjs 中的记住我的功能和令牌 [英] Remember me functionality and Token in Angularjs

查看:29
本文介绍了Angularjs 中的记住我的功能和令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里寻找更好的方法来解决我的问题.我的登录表单上有记住我的功能.用户点击记住我框,我的 API 向我发送令牌.

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?

我的想法,

  1. 创建一个 Cookie 并将令牌存储在那里.
  2. 创建本地存储.

请给我任何可能对我有帮助的建议.

Please give me any advice which might help me.

推荐答案

我会使用 document.cookie 和这样的工厂代码:

I would use document.cookie with a factory code like this:

创建一个 cookie(例如这个在一年后过期):

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

这个工厂删除了cookie:

This factory removes the cookie:

app.factory('$forget', function() {
    return function(name) {
        var cookie = name + '=;';
        cookie += 'expires=' + (new Date()).toString() + ';';

        document.cookie = cookie;
    }
});

然后每当用户成功登录时使用 $remember 缓存密钥:

Then whenever a user successfully logs in cache the key using $remember:

$remember('my_cookie_name', response.user._id);

并且在用户登录时始终检查 cookie 是否存在,否则使用标准登录名并将其保存到他们的 cookie 中.如果没有启用记住我,忘记document.cookie

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

这篇关于Angularjs 中的记住我的功能和令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆