Home > Back-end >  Adding the Bearer token to the header doesn't work as expected
Adding the Bearer token to the header doesn't work as expected

Time:11-17

I have created a Spring-Boot back-end along with an Angular front-end in order to try out JJWT, I got the back-end sorted out and I got stuck in the front-end.

So basically, I get the token when the login process is finished and then I store it in the localStorage.

I created a custom HttpInterceptor whose purpose is to add the token to each request :

@Injectable()
export class JwtRequestInterceptor implements HttpInterceptor {

intercept(request: HttpRequest<any>, handler: HttpHandler): Observable<HttpEvent<any>> {
    return handler.handle(request.clone({
        setHeaders: {
            "Authorization": `Bearer ${localStorage.getItem("jwt")}`
        }
    }))
  }
}

I then added this interceptor in the AppModule as a provider for HTTP_INTERCEPTORS :

{ provide: HTTP_INTERCEPTORS, useClass: JwtRequestInterceptor, multi: true }

The problem is when I'm making a request (from my front-end), the request is shown twice in the Network tab of the browser, first request has CORS Error status - Authorization header is present, and the second request has 403 as status, but the Authorization header is missing.

Quick disclaimer, doing a request with Postman to the back-end with the token added in the header works without a problem

Any ideas why?

CodePudding user response:

Looks like you have not enabled CORS on the backend-side.
In this case, you need to enable CORS.
See here how to enabe it in the Speing Security: https://auth0.com/blog/spring-boot-authorization-tutorial-secure-an-api-java/#Enable-CORS-in-Spring-Boot

  • Related