[英]Authentification with ember-simple-auth in before model hook
我创建了一个应用程序,需要在除一页(mobile_messages)之外的所有页面上使用电子邮件/密码进行身份验证,在该页面上需要使用刷新令牌进行身份验证。 我从JWT身份验证器扩展并覆盖了authenticate方法。 所以看起来像:
authenticate (credentials, headers) {
return new Ember.RSVP.Promise((resolve, reject) => {
this.makeRequest('/auth/mobile_token', credentials, headers)
.then((response) => {
Ember.run(() => {
try {
const sessionData = this.handleAuthResponse(response)
resolve(sessionData)
} catch (error) {
reject(error)
}
})
}, (xhr) => {
Ember.run(() => { reject(xhr.responseJSON || xhr.responseText) })
})
})
}
在mobile_messages路由上,我尝试在模型钩子之前进行身份验证。
beforeModel (transition) {
const authenticator = 'authenticator:api-token'
return this.get('session').authenticate(authenticator, {api_token: transition.queryParams.api_token}).then(() => {
}, (reason) => {
transition.abort()
this.get('notifications').error('Permission denied.', {
autoClear: true,
clearDuration: 6200
})
})
},
如果身份验证被拒绝,我需要保持在mobile_messages路由上。 但是当我输入带有令牌的路由时,我得到了下一个回溯:
Preparing to transition from '' to 'mobileMessages'
index.js:169 generated -> controller:mobileMessages {fullName:
"controller:mobileMessages"}
index.js:169 generated -> controller:aut`enter code here`henticated
{fullName: "controller:authenticated"}
index.js:169 generated -> controller:loading {fullName:
"controller:loading"}
router.js:300 Intermediate-transitioned into 'authenticated.loading'
index.js:169 generated -> route:messages-faxes {fullName:
"route:messages-faxes"}
router.js:190 Transitioned into 'login'
jquery.js:9600 POST http://localhost:3000/auth/mobile_token 500
(Internal Server Error)
好像我在从服务器得到响应之前被重定向了。 我找不到谁将我从路线重定向。 我尝试检查ApplicationRouteMixin,但是只有当您单击注销按钮时,我才获得了sessionInvalidated方法调用。 并在成功认证后进行sessionAuthenticated。
如果我推送路由正确的令牌,那么我将首先重定向到登录页面,然后触发sessionAuthenticated。 之后,我重定向到baseURL。
迫切需要解决重定向到登录页面的问题?
Ember Simple Auth使用Mixins来确定如果对用户进行身份验证/未身份验证,则应该发生的路由转换行为。
例如,如果用户未经身份验证,此混合将不允许用户停留在路线上:
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
export default Ember.Route.extend(AuthenticatedRouteMixin, {
// route code
});
您可能要使用的是UnauthenticatedRouteMixin
仅在会话未通过身份验证的情况下,此混合器才用于使路由可访问(例如,登录和注册路由)。 它定义了一个beforeModel方法,该方法将中止当前转换,如果会话已通过身份验证,则转换为routeIfAlreadyAuthenticated。
在您的路由中包括UnauthenticatedRouteMixin,如果会话未通过验证,则需要访问该路由。 例如:
// app/routes/login.js
import UnauthenticatedRouteMixin from 'ember-simple-
auth/mixins/unauthenticated-route-mixin';
export default Ember.Route.extend(UnauthenticatedRouteMixin);
加载挂钩是错误的。 我在命名路线时出错。 我创建了带有名称加载的路由,以重定向到邮件传真路由。 在这种情况下,当模型挂钩返回之前,promer ember会生成route:application_loading。 在application_loading路由中,我运行到具有UnauthenticatedRouteMixin的消息-传真路由的过渡。 此混入看到该用户未通过身份验证,并重定向到加载页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.