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

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

问题描述

现在我正在Ruby on Rails上构建一个基于AngularJS的应用程序,并使用Devise进行身份验证。当用户成功进行身份验证以及身份验证失败时,我让服务器正确响应。我想我的问题是,使用$ cookieStore,了解用户是否登录的最佳做法是什么?有一个由Rails设置的cookie称为myapp_session,但该会话并不一定意味着用户已登录。寻找有关如何使用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(['Auth', 'UserRestService', function run(Auth, UserRestService) {

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

当然,如果对服务器的任何请求返回 Http状态401 - 未经授权 ,您需要调用 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 - 未经授权的服务器响应,您可以在 $ 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.

你会发现一个好的例子这里

You will find a good example here

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

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