Цель: если пользователь переходит по защищенной ссылке, ему должно быть предоставлено всплывающее окно блокировки 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);
}
}
Служба аутентификации берет state.url и добавляет его к переменной, а затем показывает блокировку. В рамках этой службы я прослушиваю аутентифицированное событие, устанавливаю сеанс и затем перенаправляюсь на этот URL-адрес перенаправления, который был установлен.
Однако auth0 уже имеет свой собственный redirectUrl, который в настоящее время указывает на базовый URL-адрес /
. Как только он попадает туда, состояние this.redirectUrl становится неопределенным.
Как я могу решить эту проблему.