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
CodePudding user response:
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.
CodePudding user response:
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