【问题标题】:REST API and User AuthorizationsREST API 和用户授权
【发布时间】:2016-06-17 11:01:42
【问题描述】:

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

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

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

【问题讨论】:

    标签: angularjs rest session playframework


    【解决方案1】:

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

    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 端处理智能并尝试使用 Session State。

    C#参考

    HttpContext.Current.Session["Auth"]
    

    Python 参考

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

    【讨论】:

    • 我在上面的帖子中非常清楚地提到我使用Play框架,它没有会话状态的概念。
    • 只是一个建议,您确实在游戏框架中有会话,以及您如何设计 api 来管理身份验证 (playframework.com/documentation/2.5.x/…)。这意味着它会在每个 HTTP 请求标头中传递会话。
    【解决方案2】:
    1. 是的,每个请求都需要授权标头
    2. 您究竟需要保留什么?是的,使用一些服务/工厂来存储重要数据是完全可以的,这些数据将在整个应用程序中使用

    【讨论】:

      猜你喜欢
      • 2018-07-28
      • 1970-01-01
      • 2018-09-06
      • 2019-01-16
      • 2019-07-05
      • 1970-01-01
      • 2018-07-30
      • 1970-01-01
      • 2020-02-03
      相关资源
      最近更新 更多