-1

I am trying to add a header into the restTemplate, with one of its methods exchange. In header i am putting the token access, which we can access with. The error i am getting is that i am not Authorized, 401 status is giving back . Any advices what i am doing wrong?

 HttpHeaders headersAuth = new HttpHeaders();
        headersAuth.set(HttpHeaders.ACCEPT,MediaType.APPLICATION_JSON_VALUE);
        HttpEntity<?> entityAuth =  new HttpEntity<>(headersAuth);
        String urlTemplateAuth = UriComponentsBuilder.fromHttpUrl("some url")
                .encode()
                .toUriString();
        Map<String,String> queryParamsAuth = new HashMap<>();
        queryParamsAuth.put("Authorization",tokenValue); //here is my token access


            ResponseEntity <UserGetPhoneDto> userGetPhoneDtoResponseEntity = restTemplate.exchange(urlTemplateAuth,HttpMethod.GET,entityAuth,UserGetPhoneDto.class,queryParamsAuth); 
//here i am getting error of 401 status
ProgramCOder
  • 89
  • 2
  • 2
  • 10
  • Does this answer your question? [Sending GET request with Authentication headers using restTemplate](https://stackoverflow.com/questions/21101250/sending-get-request-with-authentication-headers-using-resttemplate) – Valerij Dobler Jun 28 '22 at 07:16
  • You want to set a header but fill the parameter map. Use `headersAuth.setBearerAuth(token)` instead of map or parameters. – M. Deinum Jun 28 '22 at 07:23

2 Answers2

1

You have not set token to header yet, you set it in your query parameter. You can use headersAuth.setBearerAuth() to set bearer token, or use setBasicAuth() to set username and password. Another way to put it in your header:

headersAuth.set(HttpHeaders.AUTHORIZATION, token);

OAuth2 server can retrieve your token in query parameter with name 'access_token' too.

Nam Tran
  • 643
  • 4
  • 14
0

Your code doesn't put the token into the request header.

    HttpHeaders headersAuth = new HttpHeaders();
    
    headersAuth.set(HttpHeaders.ACCEPT,MediaType.APPLICATION_JSON_VALUE);
    
    String urlTemplateAuth = UriComponentsBuilder.fromHttpUrl("some url")
            .encode()
            .toUriString();
    Map<String,String> queryParamsAuth = new HashMap<>();
    headersAuth.put("Authorization",tokenValue); //here is put it into headers
    HttpEntity<?> entityAuth =  new HttpEntity<>(headersAuth);//build entity by header
   //exchange...

You can read this document to learn more about http. https://developer.mozilla.org/en-US/docs/Web/HTTP

milkdove
  • 56
  • 1