我目前正在开发一个 Angular 独立应用程序,其中使用 angular-oauth2-oidc 进行身份验证。我已使用授权代码流成功配置身份验证,但在身份验证后将用户重定向到最初请求的 URL 时遇到问题。
这是我当前配置的片段app.config.ts:
import { APP_INITIALIZER, ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { AuthConfig, OAuthService, provideOAuthClient } from 'angular-oauth2-oidc';
import { authCodeFlowConfig } from './configurations/auth.config';
import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { APP_BASE_HREF, DatePipe } from '@angular/common';
import { FastapiInterceptorService } from './services/fastapi-interceptor.service'
function initializeOAuth(oauthService: OAuthService): Promise<void> {
return new Promise((resolve) => {
oauthService.configure(authCodeFlowConfig);
oauthService.setupAutomaticSilentRefresh();
oauthService.loadDiscoveryDocumentAndLogin().then(() => {
resolve();
});
});
}
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient (
withInterceptorsFromDi()
),
{ provide: HTTP_INTERCEPTORS, useClass: FastapiInterceptorService, multi: true},
provideOAuthClient(),
{
provide: APP_INITIALIZER,
useFactory: (oauthService: OAuthService) => {
return () => {
initializeOAuth(oauthService);
}
},
multi: true,
deps: [
OAuthService
]
},
provideAnimationsAsync(),
{ provide: APP_BASE_HREF, useValue: '/matrix' }, // Add this line to provide APP_BASE_HREF
DatePipe
]
};
如何修改此配置以确保用户在身份验证成功后重定向到最初请求的 URL?例如,如果用户尝试直接访问受保护的路由并被重定向到登录页面,如何确保他们在身份验证后重定向回预期路由?
任何帮助或指导将不胜感激。谢谢!
我尝试了以下配置:
我解决了
function initializeOAuth(oauthService: OAuthService, router: Router): Promise<void> {
return new Promise((resolve) => {
if (oauthService.hasValidAccessToken()) {
resolve();
return;
}
oauthService.configure(authCodeFlowConfig);
oauthService.loadDiscoveryDocumentAndTryLogin().then(() => {
const url = oauthService.state ?? '';
if (!oauthService.hasValidAccessToken()) {
oauthService.initImplicitFlow(router.url);
oauthService.setupAutomaticSilentRefresh();
}
else{
router.navigateByUrl(decodeURIComponent(url));
resolve();
}
});
});
}