У нас есть внешний интерфейс Angular6, который использует для аутентификации пакет angular-oauth2-oiudc . Пакет позволяет использовать только один URL-адрес перенаправления с сервера аутентификации, что является проблемой, поскольку нам нужно разрешить несколько точек входа в приложение (т. Е. Щелкнув ссылку на определенную страницу по электронной почте - по этой причине мы хотим использовать hashlocation). ). Поэтому мы отключили начальную навигацию в модуле app-routing, чтобы иметь больше контроля:
imports: [RouterModule.forRoot(ROUTES, {useHash: true, initialNavigation: false})],
Мы делаем простой вход в метод app.component.ts ngOnInit
. Я следовал другим решениям, чтобы подключить прослушиватель событий, чтобы перехватывать события маршрутизатора и фиксировать URL. Это работает для начальной навигации в приложении, однако не работает для того, чтобы оставаться на той же странице, когда вы обновляете браузер, или переходить на определенную страницу по ссылке. Я не знаю, как вызвать URL-адрес маршрута из app.component для этих случаев. Кто-нибудь делал что-то подобное?
app.component:
export class AppComponent implements OnInit, AfterViewInit {
currentUrl: string = null;
...
constructor(
storageManager: LocalStoreManager,
private toastaService: ToastaService,
private toastaConfig: ToastaConfig,
private notificationService: NotificationService,
private appTitleService: AppTitleService,
private translationService: AppTranslationService,
public configurations: ConfigurationService,
public router: Router,
private route: ActivatedRoute,
@Inject(PLATFORM_ID) private platformId: Object,
private oauthService: OAuthService) {
if (isPlatformBrowser(this.platformId)) {
this.oauthService.configure(environment.authconfig);
this.oauthService.tokenValidationHandler = new JwksValidationHandler();
}
//route event listener
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationEnd) {
console.log('URL: ', event.url);
this.currentUrl = event.url;
}
});
...
}
...
ngOnInit() {//login and redirect logic here
if (isPlatformBrowser(this.platformId)) {
this.oauthService.loadDiscoveryDocumentAndTryLogin().then(_ => {
if (
!this.oauthService.hasValidIdToken() ||
!this.oauthService.hasValidAccessToken()
) {
this.oauthService.initImplicitFlow();
}
else {
this.oauthService.loadUserProfile().then((userInfo: any) => {
const roles = userInfo.role;
});
}
this.isUserLoggedIn = this.oauthService.hasValidIdToken() && this.oauthService.hasValidAccessToken();
if(this.currentUrl){
this.router.navigate([this.currentUrl]);
} else {
this.router.navigate(['/']);
}
});
}
app-routing.module.ts доступные маршруты:
const routes: Routes = [
{ path: '', component: HomeComponent, data: { title: 'Home' } },
{ path: 'edit', component: EditComponent, data: { title: 'Edit' } },
{ path: 'home', redirectTo: '', pathMatch: 'full' },
{ path: '**', component: NotFoundComponent, data: { title: 'Page Not Found' } }
];
Конфигурация аутентификации:
authconfig: {
// Url of the Identity Provider
issuer: '[Our Identity Server]',
requireHttps: true,
// URL of the SPA to redirect the user to after login
redirectUri: 'http://localhost:4200/'
}