我正在独立使用 Angular 17。我安装了 angular-oauth2-oidc 库。结果他没有得到令牌。我在旧版本中使用 NgModule 有相同的角度应用程序,并且工作正常。你知道解决问题的方法吗?也可以将库更改为可与 Angular Standalone 一起使用的库
export class AppComponent implements OnInit {
constructor(private oauthService: OAuthService) {
this.configureOAuth();
}
private configureOAuth(): void {
const authConfig: AuthConfig = {
issuer: 'url',
redirectUri: window.location.origin,
responseType: 'code',
requireHttps: false,
clientId: 'm0063',
scope: 'openid profile email offline_access roles',
};
this.oauthService.configure(authConfig);
//this.oauthService.loadDiscoveryDocumentAndLogin();
}
ngOnInit(): void {}
login() {
this.oauthService.loadDiscoveryDocumentAndLogin().then(x => {
setTimeout(() => {
this.oauthService.initCodeFlow();
});
});
}
logout() {
this.oauthService.logOut({ customParameters: true, client_id: 'm0063' });
}
}
export const appConfig: ApplicationConfig = {
providers: [
provideAnimations(),
provideHttpClient(),
provideRouter(
appRoutes,
withPreloading(PreloadAllModules),
withInMemoryScrolling({ scrollPositionRestoration: 'enabled' }),
withViewTransitions()
),
importProvidersFrom(HttpClientModule),
provideOAuthClient( {
resourceServer: {
allowedUrls: ['localhost:4200', 'url:8080'],
sendAccessToken: true
}
}
),
provideUrl(),
}
错误:
your text
未检查的runtime.lastError:侦听器通过返回 true 指示异步响应,但消息通道在收到响应之前关闭
我尝试创建新模块并实现配置,如 ngModule 中的 For.root,但它仍然无法工作。
我正在使用 Angular 17、Angular-oauth2-oidc 和 keycloak。
这种方法对我有用:
import {Injectable} from '@angular/core';
import {AuthConfig, OAuthService} from 'angular-oauth2-oidc';
import {Observable, of} from 'rxjs';
import {environment} from '../../../environments/environment';
@Injectable({
providedIn: 'root',
})
export class AuthService {
constructor(private oauthService: OAuthService) {}
authConfig: AuthConfig = {
responseType: 'code',
scope: 'openid profile email',
redirectUri: window.location.origin,
oidc: true,
requestAccessToken: true,
showDebugInformation: true,
strictDiscoveryDocumentValidation: false,
useSilentRefresh: true,
issuer: `${environment.KEYCLOAK_URL}realms/${environment.KEYCLOAK_REALM}`,
clientId: environment.KEYCLOAK_CLIENT_ID,
};
initAuth() {
this.oauthService.configure(this.authConfig);
this.oauthService.setupAutomaticSilentRefresh();
this.oauthService.loadDiscoveryDocumentAndTryLogin();
}
login() {
this.initAuth();
this.oauthService.initCodeFlow();
}
logout() {
this.oauthService.logOut();
}
isLoggedIn(): Observable<boolean> {
return of(this.oauthService.hasValidIdToken());
}
getAccessToken(): string {
const accessToken = this.oauthService.getAccessToken();
return accessToken;
}
}
我在我的应用程序配置中提供了 oAuth2Lib,如下所示:
export const coreConfig: ApplicationConfig = {
providers: [
provideOAuthClient()
]
}
您可能还需要在独立的 app.component.ts 中提供“AuthService”,并在构造函数中调用“initAuth()”。我还没有找到更好的解决方案。
export class CoreComponent {
constructor(
private readonly authService: AuthService,
) {
this.authService.initAuth();
}
}