0

I try to use an angular injector to add a bearer token

although the code is executed, the header is not added

there are many different codes out there, I tried some of them, they all lead to the same issue

no bearer is send with the request

in the below image I stopped at clone/headers.set, but even after that step, the headers map is still empty

enter image description here

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  constructor(
    private appService: AppService
  ) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // add auth header with jwt if user is logged in and request is to the api url
    let authentication: Authentication = this.appService.getUserSession();

    const isLoggedIn = authentication && authentication.token;
    const isApiUrl = request.url.startsWith(environment.apiUrl);

    //------------------------------------- add id's
    let body = request.body;
    if(!body)
    {
        body={};
    }
    body['clientId'] = environment.clientId;
    body['clientSecret'] = environment.clientSecret;

    request = request.clone({
        body: body
    });

    //--------------------------------------- add jwt

    if(authentication)
    {
        request = request.clone(
            {
                headers: request.headers.set('Bearer', authentication.token)
            }
        );
    }

    return next.handle(request);
  }
}

thanks for helping me on this one

1 Answer 1

0

According to the clone() method prototype, you got an object property to set headers (named setHeaders)

setHeaders?: {
            [name: string]: string | string[];
        };

You should do as following

 request = request.clone(
         {
            setHeaders: {
                Authorization: `Bearer ${authentication.token}`
            }
         }
    );
Sign up to request clarification or add additional context in comments.

2 Comments

pretty sure this was the previous code I had, I'll check it out, thanks
did not work for me either. I think if it worked with this answer, it would also work for one of those in the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.