确保用户使用 cookieStore 和 AngularJS 登录或注销的最佳实践 [英] Best practice for ensure user is logged in or out using cookieStore and AngularJS

查看:23
本文介绍了确保用户使用 cookieStore 和 AngularJS 登录或注销的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在 Ruby on Rails 之上构建一个基于 AngularJS 的应用程序,并使用 Devise 进行身份验证.当用户身份验证成功和身份验证失败时,我让服务器正确响应.我想我的问题是,使用 $cookieStore,了解用户是否登录的最佳做法是什么?Rails 设置了一个名为myapp_session"的 cookie,但该会话并不一定意味着用户已登录.寻找有关如何使用 AngularJS 保持用户在线/离线管理的想法.无论解决方案如何,我仍将确保需要授权的请求得到后端的授权.

Right now I am building an AngularJS based application on top of Ruby on Rails and using Devise for authentication. I have the server responding properly when a user authenticates successfully and when authentication fails. I guess my question is, using $cookieStore, what's the best practice for knowing if a user is logged in or not? There is a cookie that gets set by Rails called "myapp_session", but that session doesn't necessarily mean a user is logged in. Looking for ideas on how to use AngularJS to keep user online/offline management. I'll still be ensuring that requests that require authorization get authorized by the backend regardless of the solution.

推荐答案

您可以创建一个指令,在应用程序加载时设置登录用户,例如,请求服务器上的当前用户会话.

You can create an directive that set up the logged user when the application loads, for example, requesting the current user session on your server.

angular.module('Auth', [
        'ngCookies'
    ])
    .factory('Auth', ['$cookieStore', function ($cookieStore) {

        var _user = {};

        return {

            user : _user,

            set: function (_user) {
                // you can retrive a user setted from another page, like login sucessful page.
                existing_cookie_user = $cookieStore.get('current.user');
                _user =  _user || existing_cookie_user;
                $cookieStore.put('current.user', _user);
            },

            remove: function () {
                $cookieStore.remove('current.user', _user);
            }
        };
    }])
;

并在 AppController 中的 run 方法中设置:

And set in your run method in AppController:

   .run(['Auth', 'UserRestService', function run(Auth, UserRestService) {

            var _user = UserRestService.requestCurrentUser();
            Auth.set(_user);
        }])

当然,如果任何对服务器的请求返回Http Status 401 - Unauthorized,则需要调用Auth.remove()服务从cookie中删除用户并将用户重定向到登录页面.

Of course if any request to the server return an Http Status 401 - Unauthorized, you need to call the Auth.remove() service to remove the user from cookie and redirect the user to login page.

我使用这种方法并且效果很好.也可以使用localStorage,但用户数据会持久化.除非您为此身份验证设置到期日期,否则我认为这不是最佳做法.

I use this approach and works very well. You can also use the localStorage, but the user data will be persisted for a long time. Unless you set an expiration date for this authentication, I don't see as best practice.

请记住始终在您的服务器站点上验证用户凭据 =)

Keep in mind to always verify the user credentials on your server site =)

要监听 401 - Unauthorized 服务器响应,您可以在 $http 请求上放置一个拦截器,如下所示:

To listen to 401 - Unauthorized server response, you can put an interceptor on your $http request, like this:

 .config(['$urlRouterProvider', '$routeProvider', '$locationProvider', '$httpProvider', function ($urlRouterProvider, $routeProvider, $locationProvider, $httpProvider) {
        $urlRouterProvider.otherwise('/home');
        var interceptor = ['$location', '$q', function ($location, $q) {

            function success(response) {
                return response;
            }

            function error(response) {

                if (response.status === 401) {
                    $location.path('/login');
                    return $q.reject(response);
                }
                else {
                    return $q.reject(response);
                }
            }

            return function (promise) {
                return promise.then(success, error);
            };
        }];

        $httpProvider.responseInterceptors.push(interceptor);
    }])

每次调用带有 401 响应,用户将被重定向到 /login 路径下的登录页面.

Every call with 401 response, the user will be redirected to login page at /login path.

你会在这里找到一个很好的例子

这篇关于确保用户使用 cookieStore 和 AngularJS 登录或注销的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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