目标:如果用户导航到受保护的链接,他们应该被给予 auth0 锁定弹出窗口以登录并被重定向到他们的预期目的地。
我有一个受保护的路由/reports,它通过 authguard 服务受到保护。
auth.guard.ts
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private authService: AuthService,
private router: Router,
private snackBar: MatSnackBar,
) {
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (!this.authService.isAuthenticated()) {
this.authService.login(state.url);
return false;
}
return true;
}
}
守卫尝试通过 state.url 登录(这是用户在被提示登录之前打算去的地方)。
auth.service.ts
@Injectable()
export class AuthService {
lock = new Auth0Lock(
environment.auth.clientID,
environment.auth.domain,
environment.auth.auth0Options,
);
jwtHelper: any;
// Store authentication data
// userProfile: any;
// accessToken: string;
// authenticated: boolean;
redirectUrl: any;
constructor(private router: Router, private jwtService: JwtService) {
this.jwtHelper = new JwtHelperService();
this.lock.on('authenticated', (authResult: any) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
console.log('NAVIGATING TO ANOTHER PAGE');
this.router.navigate([this.redirectUrl]);
}
});
this.lock.on('authorization_error', error => {
console.log('Auth Failed', error);
});
}
private setSession(authResult): void {
console.log('setting session');
console.log('here', this.redirectUrl);
this.lock.getUserInfo(authResult.accessToken, (error, profile) => {
if (error) {
throw new Error(error);
}
this.setProfileToken(authResult.idToken);
localStorage.setItem('token', authResult.idToken);
localStorage.setItem('profile', JSON.stringify(profile));
});
}
getLoggedInUser() {
const user = localStorage.getItem('profile');
return JSON.parse(user);
}
setProfileToken(idToken): void {
this.jwtService.generate(idToken).subscribe((res) => {
if (res) {
localStorage.setItem('profile_token', res.token);
}
}, (err) => {
console.log(err);
});
}
login(redirectUrl: string = '/') {
this.redirectUrl = redirectUrl;
console.log('login', this.redirectUrl);
this.lock.show();
}
logout() {
localStorage.removeItem('profile');
localStorage.removeItem('token');
localStorage.removeItem('profile_token');
this.router.navigate(['/']);
}
isAuthenticated() {
const token = localStorage.getItem('token');
return !this.jwtHelper.isTokenExpired(token);
}
}
auth 服务获取 state.url 并将其添加到变量中,然后显示锁。在此服务中,我正在侦听经过身份验证的事件,设置会话,然后重定向到设置的此重定向 url。
但是 auth0 已经有自己的 redirectUrl ,它当前指向基本 url /。一旦它到达那里,状态 this.redirectUrl 变得未定义。
我怎么解决这个问题。