2

I am using HTTPClient Module of Angular 4 for retrieving data from a database. The corresponding service has the following method,

getPosts() {
        const httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
        // tslint:disable-next-line:max-line-length
        httpHeaders.set('Authorization for JWT', 'Token');
        return this.http.get('http://localhost:9090/api/user' + '?user_id=' + this.user.id.toString(),
    {headers: httpHeaders,
    responseType: 'json'});
    }

I am calling this method from a component as follows,

this.Servie.getPosts().subscribe(pos => {
     console.log(pos);
   });

But I am getting an error as follows in server side,

java.lang.RuntimeException: JWT Token is missing

error at the client side,

Failed to load http://localhost:9090/api/user?user_id=1: Response for preflight has invalid HTTP status code 500.

Please correct me where I am going wrong?

I Have made changes according to discussion below, but still problem is there as follows, I think I have messed it up right now, I made the following changes as follows,
This is the code written in service,

const httpHeaders = new HttpHeaders()
    .set('Content-Type', 'application/json')
    // tslint:disable-next-line:max-line-length
    .set('RequestAuthorization', 'Bearer ' + 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI5ODg0NjUxMjMzIiwidXNlcklkIjoiNSJ9.gwiZcx5I8rInXJGANvS9twupXjdjrzFdZNZ0K85u-KA8LXXDgDf27mUzUoiEyxRMg');
    return this.http.get('http://localhost:9090/user' + '?user_id=' + this.user.id.toString(),
{headers: httpHeaders});

And i am calling the above service as follows,

    this.userServie.getPosts().map((res: Response) =>
   console.log(res.text()));

But the service is not hitting, i am not seeing the GET method in network tab of browser development tools. Where i am wrong ? Please correct me.

Anil
  • 1,748
  • 8
  • 32
  • 67
  • 3
    Correct me if I'm wrong but shouldn't the header be ('Authorization' , 'Bearer ' + jwt_token_here) –  Mar 20 '18 at 09:40
  • Bearer?, can you please tell me what is this? – Anil Mar 20 '18 at 09:46
  • https://stackoverflow.com/a/25850821/5283119 Here is a link which explains bearer and refresh tokens pretty well. Yeah you can set the content type application/json but it doesn't really matter to use a JWT token. The JWT token is the type of authorization to tell your app you are who you say you are. –  Mar 20 '18 at 09:50

2 Answers2

1

Headers have defined values.

httpHeaders.set('Authorization for JWT', 'Token');

Should be

httpHeaders.set('Authorization', 'Bearer ' + token);

If you provide random tokens to your server, of course it will tell you that the token is missing. In your case, you're sending this

Authorization for JWT --> Token
  • 1
    I have given the correct authorization token, the same has worked in postman software, here i have not given due to security purpose. – Anil Mar 20 '18 at 09:46
  • You should not do that. See how it is misleading. And apparently you didn't use `Bearer` in your token, so maybe you should try what I answered. –  Mar 20 '18 at 09:48
  • (And there is no security breach if you just give us your code, don't worry) –  Mar 20 '18 at 09:49
  • Ok, can you please tell me, what is `Bearer`? I am kinda new to this. Please help me to get the point. Thank You. – Anil Mar 20 '18 at 09:50
  • Bearer means `the one that bears` in english, and `to bear = to carry`. See it as something that bears your token. This is an authentication scheme. You can find **[more information here](https://swagger.io/docs/specification/authentication/bearer-authentication/)** –  Mar 20 '18 at 09:53
  • I have corrected my mistake as follows, `httpHeaders.set('Authorization', 'Bearer' + 'AuthToken eyJh`)` But still I am getting the same error. – Anil Mar 20 '18 at 09:59
  • 1
    Because it is `('Authorization', 'Bearer ' + 'eyJh')`. Be sure to put a space between bearer and your token too. –  Mar 20 '18 at 10:01
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/167164/discussion-between-anil-and-trichetriche). – Anil Mar 20 '18 at 10:14
0

Once you figure out the real headers to send I think you'll have 2 problems:

Issue #1

HttpHeaders class is immutable

So you need to have something like this

const httpHeaders = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Authorization', 'Bearer [yourTokenHere]')

instead of declaring httpHeaders and calling set without chaining the call

const httpHeaders = new HttpHeaders();
//The line below has no effect on the httpHeaders instance
httpHeaders.set('Authorization', 'Bearer [yourTokenHere]');

Issue #2

Also, did you make sure that CORS was configured properly on your java server?

You are getting an error about missing token for the preflight request (i.e. the one with the Options method). AFAIK, browsers do not send custom headers like Authorization for preflight requests. So, the server should not check the token for the OPTIONS request (otherwise, you'll always end up getting 401 as tokens won't be sent)

David
  • 33,444
  • 11
  • 80
  • 118
  • Hi David, I'm trying configure CORS, but not getting it properly , how can I do it plz? – Anil Mar 20 '18 at 12:14
  • It depends on your server, obviously java, which I don't know. I'm sure other SO users had that problem – David Mar 20 '18 at 13:15
  • With reference to the [link](https://spring.io/guides/gs/rest-service-cors/) , i have configured CORS in the server as follows, `@RestController @CrossOrigin(origins = "http://localhost:9090") public class UserController { @Autowired private UserService userService; @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity> getAvailable(@RequestParam("user") String user){ } }` – Anil Mar 20 '18 at 13:40
  • Does it work? There might be some more to do https://stackoverflow.com/questions/37516755/spring-boot-rest-service-options-401-on-oauth-token and https://spring.io/blog/2015/06/08/cors-support-in-spring-framework If you read the comments on the second link, you might have to do more work if using sprint 4.1 or older. But once again, I don't know java – David Mar 20 '18 at 14:02