REST API和用户授权

时间:2016-06-16 21:29:23

标签: angularjs rest session playframework

我使用Play Framework提供了一组REST API。我现在将使用Angular JS构建UI层。它是一个用户可以登录的门户应用程序。我现在有两个问题:

  1. Angular JS应用如何针对REST API进行自我授权?我是否应该为每个请求进行授权,还是可以使用一些防火墙规则,只允许从运行Angular JS应用程序的计算机进行访问?

  2. 如何管理会话状态? Play应用程序服务器纯粹是无状态的,我希望保持会话状态远离REST API。所以这让我离开会话状态与Angular JS App。这是可取的吗?

2 个答案:

答案 0 :(得分:0)

  1. 是的,您需要在每个请求中使用授权标头
  2. 你究竟需要保留什么?是的,使用一些服务/工厂存储重要数据是完全可以的,这些数据将在整个应用程序中使用

答案 1 :(得分:0)

对于您的auth标头,您可以使用拦截器。下面是一个通用代码,可以做得更好:

app.factory('authInterceptor', function ($q, $injector, cookie, $location, models) {
return {
    request: function (config) {
        config.headers = config.headers || {};
        // if this request is not to authenticate or logout, then refresh the existing token (if possible)
        if (config.url.indexOf("authenticate") < 0 && config.url.indexOf("logout") < 0 && config.url.indexOf("login") < 0) {
            var $http = $injector.get('$http');
            $http.post(Config.api + '/authenticate/refresh').success(function (data) { }).error(function (data) { $location.path("/login"); });
        }
        else
            config.headers.Authorization = 'Bearer ' + cookie.getObject(constant.ckAuth).token;
        return config || $q.when(config)
    },
    response: function (response) { return response || $q.when(response); },
    responseError: function (response) { return $q.reject(response); }
    };
});

您可以使用JWT进行身份验证并将其存储在$rootscope / $scope中,如果您可以使用$cookies。尝试在任何客户端对象中存储数据时,您需要了解它将在浏览器(控制台)本身中可见。因此,请在API的最后处理智能并尝试使用会话状态。

C#参考

HttpContext.Current.Session["Auth"]

Python参考

import requests 
s = requests.Session() -- Python Reference