我正在使用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/routes/router.coffee 中:
App.Router.map ->
@route 'login'
# other routes as required...
在 app/routes/application.coffee 中:
App.ApplicationRoute = App.Route.extend Em.SimpleAuth.ApplicationRouteMixin
在 app/routes/protected.coffee 中:
App.ProtectedRoute = Ember.Route.extend Em.SimpleAuth.AuthenticatedRouteMixin
在 templates/login.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 扩展或使用受保护的路由混合。
您的服务器将需要在上面配置的服务器令牌端点处处理 Oauth 2 请求和响应。这很容易做到,Section 4.3 of RFC 6749 描述了如果您的服务器端框架没有内置支持 Oauth2 的请求和响应。但是,您将需要在您的服务器上存储、跟踪和过期这些令牌。有一些方法可以避免存储令牌,但这超出了问题的范围:)
我已经回答了后端问题并提供了用于用户身份验证、API 授权和令牌身份验证的示例 Rails 示例代码here