Ember v4+Ember Simple Auth:令牌失效时按路由前缀重定向对应登录页
解决Ember Simple Auth认证异常时的定向跳转问题
完全可以实现这个需求,核心是利用Ember Simple Auth的认证钩子捕获异常场景,结合当前路由/URL前缀判断完成针对性重定向。以下是具体实现方案:
1. 捕获认证异常并获取触发路由
在认证路由基类(如app/routes/authenticated.js)中重写sessionInvalidated钩子——该钩子会在JWT过期、凭证无效等认证失效场景自动触发:
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; import Route from '@ember/routing/route'; export default class AuthenticatedRoute extends Route.extend(AuthenticatedRouteMixin) { sessionInvalidated() { // 获取触发异常的当前路由名称与URL const currentRouteName = this.router.currentRouteName; const currentUrl = this.router.currentURL; // 可选:存储当前路由/URL,用于登录成功后跳转回原页面 this.session.store.set('attemptedRoute', currentRouteName); this.session.store.set('attemptedUrl', currentUrl); // 执行自定义重定向逻辑 this.redirectToTargetLogin(currentUrl); } redirectToTargetLogin(currentUrl) { // 根据URL前缀判断用户类型,跳转到对应登录页 if (currentUrl.startsWith('/admin')) { this.transitionTo('admin.login'); } else if (currentUrl.startsWith('/user')) { this.transitionTo('user.login'); } else { // 兜底逻辑,默认跳转至普通用户登录页 this.transitionTo('user.login'); } } }
2. 让所有认证路由继承基类
确保需要权限验证的用户路由(/user/*下的路由)和管理员路由(/admin/*下的路由)都继承上述基类,实现统一异常处理:
管理员路由示例
// app/routes/admin/dashboard.js import AuthenticatedRoute from '../authenticated'; export default class AdminDashboardRoute extends AuthenticatedRoute {}
普通用户路由示例
// app/routes/user/profile.js import AuthenticatedRoute from '../authenticated'; export default class UserProfileRoute extends AuthenticatedRoute {}
3. 登录成功后跳转回原路由(可选)
如果需要用户登录后回到触发异常的页面,可在登录路由的认证回调中读取存储的路由信息:
// 以管理员登录页为例 import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; export default class AdminLoginRoute extends Route { @service session; async submitLogin(credentials) { try { await this.session.authenticate('authenticator:jwt', credentials); const attemptedRoute = this.session.store.get('attemptedRoute'); if (attemptedRoute) { this.transitionTo(attemptedRoute); // 清除已使用的路由记录 this.session.store.remove('attemptedRoute'); } else { // 默认跳转至管理员首页 this.transitionTo('admin.dashboard'); } } catch (error) { // 处理登录失败逻辑 } } }
额外注意事项
- 确保JWT认证器已正确配置过期检测,Ember Simple Auth的JWT认证器会自动识别令牌过期并触发
sessionInvalidated钩子。 - 如果是API返回401错误触发的认证失效,需在应用的AJAX错误处理器中主动调用
session.invalidate(),触发统一的异常处理流程:
// app/services/ajax.js(基于ember-ajax) import AjaxService from 'ember-ajax/services/ajax'; import { inject as service } from '@ember/service'; export default class Ajax extends AjaxService { @service session; async handleResponse(status) { if (status === 401) { await this.session.invalidate(); } return super.handleResponse(...arguments); } }
内容的提问来源于stack exchange,提问作者Vladislav Rastrusny
相关产品推荐
相关产品推荐

