EmberJS Rails API security

EmberJS Rails API security

本文关键字:security API Rails EmberJS      更新时间:2023-09-26

Setup是一个使用JSON api的rails后端Ember前端。

一切都很好,但还是出现了一些问题:

如何确保只有emberjs应用程序使用api?我不希望脚本编写人员编写应用程序来使用后端api。

这一切似乎都很不安全,因为EmberJS应用程序将以.js文件的形式传入客户端。

如果每个人都可以访问JS控制台,我如何确保用户是真正的用户?

您可以扩展RESTAdapter并覆盖ajax方法以在散列中包含您的身份验证令牌,并且您需要确保您的控制器验证该令牌。

在我的环境(.NET)中,我在我的应用程序渲染的文档的隐藏字段中有身份验证令牌,所以我的ajax覆盖看起来像这样:

App.Adapter = DS.RESTAdapter.extend({
  ajax: function(url, type, hash, dataType) {
      hash.url = url;
      hash.type = type;
      hash.dataType = dataType || 'json';
      hash.contentType = 'application/json; charset=utf-8';
      hash.context = this;
      if (hash.data && type !== 'GET') {
        hash.data = JSON.stringify(hash.data);
      }
      var antiForgeryToken = $('#antiForgeryTokenHidden').val();
      if (antiForgeryToken) {
          hash = {
            'RequestVerificationToken': antiForgeryToken
          };
      }
      jQuery.ajax(hash);
    }
});

令牌可以来自cookie或您定义的任何内容,只要您能够将其包含在请求头中并让控制器验证它(可能在before_filter中),它应该足够了。

然后在Store中,传递新的适配器而不是默认的(RESTAdapter)

App.Store = DS.Store.extend({
    revision: 12,
    adapter: App.Adapter.create()
})

注意: RESTAdapter#ajax将被更改为支持Ember.RSVP,使此覆盖弃用。它必须在下一个发行版之后更新,但对于版本12应该是可以的。

我正在使用Ember Simple Auth来进行用户身份验证和API授权。

我使用Oauth 2用户密码授予类型对用户进行身份验证,并通过承载令牌的方式授权应用程序,该令牌必须在所有未来的API请求中发送。这意味着用户在客户端应用程序中输入他们的用户名/电子邮件和密码,然后通过HTTPS发送到服务器以获得授权令牌,可能还有刷新令牌。所有请求必须通过HTTPS进行,以保护承载令牌的泄露。

我在app/initializers/auth:

Em.Application.initializer
  name: 'authentication'
  initialize: (container, application) ->
    Em.SimpleAuth.Authenticators.OAuth2.reopen
      serverTokenEndpoint: 'yourserver.com/api/tokens'
    Em.SimpleAuth.setup container, application,
      authorizerFactory: 'authorizer:oauth2-bearer'
      crossOriginWhitelist: ['yourserver.com']
在app/controllers/login.coffee:

App.LoginController = Em.Controller.extend Em.SimpleAuth.LoginControllerMixin,
  authenticatorFactory: 'ember-simple-auth-authenticator:oauth2-password-grant'
在app/线路/router.coffee:

App.Router.map ->
  @route 'login'
  # other routes as required...
在app/线路/application.coffee:

App.ApplicationRoute = App.Route.extend Em.SimpleAuth.ApplicationRouteMixin
在app/线路/protected.coffee:

App.ProtectedRoute = Ember.Route.extend Em.SimpleAuth.AuthenticatedRouteMixin

模板/登录。hbs(我使用Ember EasyForm):

{{#form-for controller}}
  {{input identification
          label="User"
          placeholder="you@example.com"
          hint='Enter your email address.'}}
  {{input password
          as="password"
          hint="Enter your password."
          value=password}}
  <button type="submit" {{action 'authenticate' target=controller}}>Login</button>
{{/form-for}}

为了保护路由,我只需要从App.ProtectedRoute扩展或使用受保护的路由mixin。

您的服务器需要在上面配置的服务器令牌端点处处理Oauth 2请求和响应。这很容易做到,RFC 6749的4.3节描述了如果你的服务器端框架没有内置支持Oauth2的请求和响应。但是,您需要在服务器上存储、跟踪和过期这些令牌。有一些方法可以避免存储令牌,但这超出了问题的范围:)

我已经回答了后端问题,并提供了示例rails示例代码用于用户身份验证,API授权和令牌身份验证在这里