Search code examples
javaweb-serviceshttpurlconnectionjson-web-token

How to send back a JWT token with HttpURLConnection in java?


I am using an API to get some information. At the beginning of each session you need to get a JWT token to be able to send requests to the API. After I've got the token and I try to send a request, I get an error saying I'm unauthorized, which is fair since I did not attach the token in my request. The problem is that the documentation for the API does not explain how to do this, and I haven't been able to find it anywhere else either. How do I do this? I am doing this is Java and is using their own HttpURLConnection. Hopefully you understand what I mean.

Thank you in advanced!


Solution

  • It depends on how the web-service (API) wants to have the token represented.

    Common are:

    • HTTP request headers (problem for XHR requests)
    • query parameters (bad idea because of caching/logging)
    • form fields (not universally useable)
    • URL segment (bad idea because of caching/logging)
    • certain cookies with the token as value (transparent) or
    • authentication header (typical)

    The Authentication headers as defined in HTTP RFCs are typically be used with the Basic or Digest authorization scheme. In case a string (token) authenticates the bearer of that token, the "Bearer" scheme is used (for example defined for OAuth2 in RFC6750).

    You would use

    uc.setRequestProperty("Authorization","Bearer " + jwt); 
    

    for this.