2

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]

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

Access to XMLHttpRequest at '127.0.0.1:8080/api/token' from origin 'localhost:4200' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response. backend.service.ts:95 token err= {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":"127.0.0.1:8080/api/… failure response for 127.0.0.1:8080/api/token: 0 Unknown Error","error":{"isTrusted":true}}
I have enabled CORS in the server
I did what you said and also enabled CORS to allow the header Authorization. I had not allowed that in the back-end. with both of these it worked fine. Thanks a lot
This looks like the related issue: github.com/auth0/angular2-jwt/issues/593

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.