3mr
3mr

Reputation: 342

angular-jwt token does not get sent in my http request headers

In my angular application, I send an http GET request to an end-point /api/token of the back-end server as shown below and receive the token.

backend.service.ts

  authenticate(userName: String, passwd: String){

      this.myHttpclient.get(AppSettings.API_ENDPOINT + "token", {responseType: 'text'}).subscribe(res=>{
        this.isLoggedIn = true;
        this.receivedJWT = res;
        localStorage.setItem('access_token', res);
        console.log("Token saved = " + localStorage.getItem('access_token'));
        this.router.navigate(['home'])
      },
      errorResponse=>{
        console.log("token err= " + JSON.stringify(errorResponse));
        this.serverError = errorResponse["error"];
        setTimeout(() => {
          this.serverError = null;
        }, 3000);
        this.router.navigate([''])
      })
  }

I can see the "Token saved = " log with the token when I log-in.

In the following method I am making an http POST after login

backend.service.ts

createNewPage(title:string, content:string){
    this.myHttpclient.post('http://127.0.0.1:8080/api/pages',
      {
        name : title,
        markdown : content
      }
    ).subscribe(res=>{

      if (res['success'] === true)
      {
         this.saveResult = "Saved Successfully";
         this.router.navigate(['home']);  
      }
      else
      {
        this.saveResult = "Save Failed";
      }

    });

  }

My app.module.ts has the imports as below to support the angular-jwt

imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    HttpClientModule,
    MaterialModule,
    FlexLayoutModule,
    FormsModule,
    MatInputModule,
    JwtModule.forRoot({
      config: {
        tokenGetter: function  tokenGetter() {
          console.log("tokenGetter called = " + localStorage.getItem('access_token') )
          return     localStorage.getItem('access_token');
        },
        whitelistedDomains: ['http://127.0.0.1:8080'],
        blacklistedRoutes:['http://127.0.0.1:8080/api/token/']
      }
    })

  ]

my POST does not stamp the JWT token in the header despite the end point is in the whitelist.

It gives the below erro

HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "http://127.0.0.1:8080/api/pages", ok: false, …}
error: "Unauthorized"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://127.0.0.1:8080/api/pages: 401 Unauthorized"
name: "HttpErrorResponse"
ok: false
status: 401
statusText: "Unauthorized"
url: "http://127.0.0.1:8080/api/pages"
__proto__: HttpResponseBase

And the request Header contains the below fields but not the "Authorization"

Accept: application/json, text/plain, */*
Content-Type: application/json
Origin: http://localhost:4200
Referer: http://localhost:4200/createPage?title=title%201&new=true
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Mobile Safari/537.36

I can't figure out what's wrong here. Even the JWT is received and stored as per the logs and I have done all the required as I understand to make the token get packed in the requests. but still id does not.

Is there anything I have missed here ? Please help

The angular-jwt version I am using is @auth0/[email protected]

Upvotes: 2

Views: 2185

Answers (1)

moha noorani
moha noorani

Reputation: 152

add url in whitelist without http:// or https://

Upvotes: 4

Related Questions