【发布时间】:2018-08-11 07:37:00
【问题描述】:
我正在尝试将 auth0 集成到我的 Angular 应用程序中。
Auth0 登录事件流程如下所示。
Angular 页面显示 auth0 登录小部件(显示登录小部件的代码位于服务内部:
AuthService)。用户从登录小部件中选择身份验证提供程序(例如:使用 google 登录)。
浏览器被重定向到身份验证提供程序。
用户在身份验证提供程序中输入凭据。
浏览器被重定向回 Angular 站点,即配置的回调 URL。就我而言,这是一个显示加载指示器的页面(因为登录仍未完成)。
使用身份验证令牌从 auth0 登录小部件触发回调事件。
在回调内部,进行 REST 调用以获取有关用户的更多信息。
当 REST 调用完成时,在将检索到的用户信息保存到本地存储后,调用
router.navigateByUrl('/home')返回主页。
但是,当我调用router.navigateByUrl('/home') 时,导航不会发生。但是,如果我在大约 5 秒超时后调用 router.navigateByUrl('/home'),则导航成功。我怀疑要进行导航,浏览器加载应该在调用navigateByUrl() 时完成。
有没有人知道一种可靠地进行导航而不使用超时的方法?
下面是AuthService 代码。
@Injectable()
export class AuthService {
lock = new Auth0Lock(
'my_client_id',
'my_auth0_sub_domain',
{
auth: {
redirectUrl: window.location.origin + '/auth_loading',
responseType: 'token',
scope: 'openid'
}
}
);
userProfile: Object;
constructor(public router: Router) {
this.userProfile = JSON.parse(localStorage.getItem('profile'));
this.lock.on("authenticated", (authResult: any) => {
localStorage.setItem('id_token', authResult.idToken);
this.lock.getProfile(authResult.idToken, (error: any, profile: any) => {
if (error) {
alert(error);
return;
}
localStorage.setItem('profile', JSON.stringify(profile));
this.userProfile = profile;
setTimeout(() => {
this.router.navigateByUrl('/home'); //This only works because of the timeout
}, 5000);
});
});
}
public login() {
this.lock.show(); //This shows the auth0 login widget
}
}
【问题讨论】:
-
请贴出相关代码。 :-)
-
@Pengyy 用代码更新问题
-
您的代码看起来不错,您是否在不使用超时时遇到任何错误?
-
@Pengyy 不,我没有收到任何错误。此外,
navigateByUrl()返回的承诺也不会导致错误。 -
这听起来很有线。也许您应该使用 stackbliz 或 plunker 重现您的场景,让其他人帮助您。