Issue
I'm working with an Angular v17 app configured in standalone mode, experiencing issues integrating with Keycloak libraries. Specifically, Keycloak isn't automatically appending the authorization header to backend requests. For security reasons, I prefer not to manually handle the Authorization Token.
- I installed Keycloak libs "npm install keycloak-angular"
- I added a provider for the Keycloak init
- I added some test code to signin and execute a request
All this code is working well with Angular non standalone (NgModule). But since I switched to standalone in angular 17, something is fishy.
To test my code, I have configured an Interceptor: authInterceptorProvider. That is adding the Token manually to each request. Works well. But I don't want to handle tokens by hand...
What might I be missing or configuring wrong?
Code bits (image upload is not working at the moment)
Here my simplyfied Application config
export const initializeKeycloak = (keycloak: KeycloakService) => {
return () =>
keycloak.init({
config: {
url: 'http://localhost:8180/',
realm: 'balbliblub-realm',
clientId: 'blabliblubi-public-client',
},
initOptions: {
pkceMethod: 'S256',
redirectUri: 'http://localhost:4200/dashboard',
},
loadUserProfileAtStartUp: false
});}
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes),
provideHttpClient(
withFetch(),
withXsrfConfiguration(
{
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN',
})
),
authInterceptorProvider,
importProvidersFrom(HttpClientModule, KeycloakBearerInterceptor),
{
provide: APP_INITIALIZER,
useFactory: initializeKeycloak,
multi: true,
deps: [KeycloakService],
},
KeycloakService,
]};
Here my AppComponent
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent implements OnInit {
title = 'testy';
public isLoggedIn = false;
public userProfile: KeycloakProfile | null = null;
constructor(private readonly keycloak: KeycloakService,
private http: HttpClient) { }
public async ngOnInit() {
this.isLoggedIn = await this.keycloak.isLoggedIn();
if (this.isLoggedIn) {
this.userProfile = await this.keycloak.loadUserProfile();
}
}
login() {
this.keycloak.login();
}
protected loadAbos() {
this.http.get<Abo[]>('http://localhost:8080/api/abos?email=' + this.userProfile?.email, { observe: 'response',withCredentials: true })
.pipe(
catchError(err => this.handleError("Could not load abos", err)),
/// if no error occurs we receive the abos
tap(abos => {
console.info("loaded abos", abos);
})
).subscribe()
}
Thanks 4 your help <3