The default behavior of Angular-Keycloak does not include automatically attaching the bearer token to my http requests

I'm currently working on integrating keycloak-angular into my project, but I'm facing an issue with setting the bearer token as the default for my HTTP requests.

"keycloak-angular": "9.1.0" "keycloak-js": "16.0.0" "Angular": "13.0.2"

    function initializeKeycloak(keycloak: KeycloakService) {
  return async () =>
   await keycloak.init({
      config: {
        url: 'https://127.0.0.1:8443/auth',
        realm: '*****',
        clientId: '****',
      },
      initOptions: {
        onLoad: 'login-required',
        checkLoginIframe: false,
      },
      loadUserProfileAtStartUp: true,
      enableBearerInterceptor: true,
      bearerExcludedUrls: [],
      bearerPrefix:'Bearer '
    });
}



 @NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    CoreModule,
    BrowserModule,
    KeycloakAngularModule,
    AppRoutingModule
  ],
  providers: [
    { provide: LOCALE_ID, useValue: 'it' },
    {
      provide: APP_INITIALIZER,
      useFactory: initializeKeycloak, 
      multi: true,
      deps: [KeycloakService]
    },
  ],
  bootstrap: [AppComponent]
})

Answer №1

To enhance the security of your API calls, it is imperative to utilize an HttpInterceptor in order to include custom headers for each call. Start by creating your interceptor and integrating it into AppModule.

providers: [
 {
   provide: HTTP_INTERCEPTORS,
   useClass: ApiInterceptor,
   multi: true,
 }
],

Proceed to implement the intercept function as follows:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  request = request.clone({
    setHeaders: {
      Authorization: `Bearer #YOUR_TOKEN_HERE#`
    }
  });

  return next.handle(request);
}

Answer №2

Instead of utilizing the HttpClient to make requests in my scenario, I opted to use fetch directly, which bypasses Angular's interception.

If you are experiencing issues with a HttpInterceptor not functioning properly, double check that HttpClient is being used for making requests.

I switched from using fetch(...) to http.get(...) and it resolved the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sorting in the TypeScript/Angular table is functioning properly on every column except for the initial one

Even after carefully following the information provided in the official documentation and implementing the example as suggested, I'm still struggling to sort my first column in descending order. Whenever I attempt to sort by another column and then cl ...

How to use D3 to add arrow directions to an SVG path

Within my svg path lies the representation of a shuttle track used in manufacturing processes. Every shuttle on this track moves in a distinct direction, and I wanted the svg path to visually indicate these directions for easy reference. Initially, I tried ...

Encountering an issue with a custom hook causing an error stating "Attempting to access block-scoped variable 'X' before its declaration."

Currently, I am in the process of developing my initial custom hook. My confusion lies in the fact that an error is being displayed, even though the function is defined just a few lines above where it's invoked. Here is the relevant code snippet: f ...

Oops! An issue occurred while trying to compile the file constructor.d.ts in the common-behaviors folder of @angular/material/core. The error message received was: "error TS1005: ';'

Switching from Bootstrap to Angular Material caused an unexpected error when trying to run ng serve: Error: node_modules/@angular/material/core/common-behaviors/constructor.d.ts:14:64 - error TS1005: ';' expected. The errors encountered include: ...

Can Bun automatically bundle my TypeScript files when I save them in VS Code?

Is it feasible for Bun to bundle my TypeScript upon saving a file in VS Code? The instruction manual suggests running bun run index.ts in the command line and including it in the package.json in this manner. However, I am unsure how to automate this proce ...

How to show ngFor value from Angular in a separate tag

I have a list of companies that I want to display in the following format: <div class="col-md-4"> <select ngModel="selectedCompany" style="width:400px;"> <option *ngFor="let x of mycompanylist&q ...

The default value in an Ionic select dropdown remains hidden until it is clicked for the first time

Having an issue with my ion-select in Ionic version 6. I have successfully pre-selected a value when the page loads, but it doesn't show up in the UI until after clicking the select (as shown in pic 2). I'm loading the data in the ionViewWillEnt ...

Angular 5 - Keeping track of variable updates

I've searched various topics on this issue, but none seem to address my specific problem. I need a way to detect changes in the properties of a component without having to convert the variable into an array or iterable. I tried using Subject, but coul ...

Innovative approaches to enhancing Feathers services through the use of relational data in design patterns

I'm in the process of developing a straightforward application that involves a one-to-many relationship between data entities. Specifically, I am working with feathers js and sequelize (utilizing sqlite) to create a system where each site can have mul ...

Angular's responsiveness is enhanced by CSS Grid technology

I am attempting to integrate a CSS grid template that should function in the following manner: Columns with equal width 1st and 3rd rows - 2 columns 2nd row - 3 columns Order = [{ details:[ { key: '1', label ...

Having trouble getting TypeScript to compile on Visual Studio Online TFS?

Currently, I am utilizing Typescript 1.7 within an MVC environment. Locally, my Typescript functions properly and compiles without any issues. However, when integrating with visualstudioonline TFS for continuous integration to an azure website, I have enc ...

Troubleshooting a cross-component property problem involving a fetch request within a subscription

My current objective is to utilize ActivatedRoute parameters to make a fetch request and update a class property with the fetched data. Progress has been made on making the request, but I am facing difficulties in getting the fetched data to the specific c ...

Guide to adding annotations to a PDF document using Angular 2

As a novice in the field of Angular development, I am seeking guidance. Currently, I have an application that displays PDF files. My goal is to be able to annotate and make changes on these PDF files by adding drawings such as circles, lines, or text. Ho ...

In Typescript, interfaces are required to have properties written in Pascal Case instead of camel Case

Currently, I am facing a strange issue in my ASP.NET 5 application where I am using Angular 1.4 with TypeScript and RXJS. Somehow, during the runtime, all my interface properties are getting converted from camel casing to Pascal casing. This unexpected beh ...

Transform angularjs directive into angular 10

After stumbling upon this intriguing code snippet, I decided to integrate it into my angular project: 'use strict'; /** * A mesmerizing floating text animation */ angular.module('g1b.text-animation', []). directive('textAnimatio ...

The cache-control header is not being included in the response header in the express app

I am facing an issue where the Cache-Control header is not getting added to the document request in my express / node server. My code successfully adds other headers, but for some reason, it fails when trying to add Cache-Control and I'm unsure why. ...

Is it possible to verify or authenticate the properties received directly from the associated type or interface?

Looking for a more efficient way to handle validation in my component that takes an array of tabs and children as props. I would like to check if the children provided are the same length as the tabs array directly from the type declaration or any cleaner ...

Incorporate SVG files into a TypeScript React application using Webpack

I am trying to incorporate an SVG image into a small React application built with TypeScript and bundled using Webpack. However, I am encountering an issue where the image is not displaying properly (only showing the browser's default image for when n ...

What is the specific category of Mongoose.startSession in the realm of Typescript?

In my Express/Typescript project with mongoose, I implemented a loader as follows: import mongoose from 'mongoose'; import { Db } from 'mongodb'; import config from '../config'; export default async (): Pr ...

Ionic: Fixed button located at the bottom of a specific ion-slide

I've been creating a series of slides with questions, and the final slide serves as a summary of the previously answered questions. I want to ensure that the submit button is always visible at the bottom of this last slide. However, I've encounte ...