Search code examples
spring-boothttp-headersjwtaccess-token

How to get the access token sent in as header with Autentication Basic in Springboot


I have completed my most of the project but now I am stuck with a new problem. I have to extract the access token from the request which will be in header in Authentication Basic. This is confusing as first I used a simple GET method and was sending the access token in the request itself and extracting that with the use of @RequestParam. I have asked a similar question before but that was for the simple request from the request itself and now I have to do that from the header.

 @GetMapping("/persons")
     public String loadPersons(@RequestParam("access_token") String access_token) throws  ParseException{
        String decode_token = pd.testDecodeJWT(access_token);
        String token = pd.jsondata(decode_token);
........................ More Code........................

I want to get that token from the request in Authentication Basic format.

I have tried some YouTube tutorials but as I have already done my project almost completely, I want to make minimum changes to it so that no further errors pop up.

Thanks in Advance


Solution

  • To get the value from the HTTP header , you can use @RequestHeader("headerValue") .

    But what your question confuse me is that you are using Basic Authentication or JWT ? Basic Authentication is only about username and password and is nothing to do with the access token. It requires a HTTP header with the format :

    Authorization: Basic <credentials>
    

    where <credentials> is Base64Encode(username:password).

    On the other hand , if you use access token formatted in JWT , the common practise is use Bearer in the "Authorization" header :

    Authorization: Bearer <JWT>
    

    So whatever you use , my advice is to use @RequestHeader("Authorization") to get value of the Authorization header first .Then decode the value according to your actual authentication mechanisms:

     @GetMapping("/persons")
     public String loadPersons(@RequestHeader("Authorization") String authHeader) throws  ParseException{
          //decode authHeader
    }