PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 4, 2022

[FIXED] How to add the header into RestTemplate

 September 04, 2022     authentication, java, spring-boot, token     No comments   

Issue

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

Solution

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.



Answered By - Nam Tran
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing