title: How to add the bearer token that is currently added to the response's auth header, to the response body?
body: <p>I implemented authorization to my SpringBoot API by using the bearer token, which when login is successful is added to the response's 'Authorization' header, this token then needs to be read by the login fetch method of my React project and added to the subsequent request 'authorization' headers.</p>
  <p>Unfortunately though I have been told this is not possible using Fetch so I am now trying to refactor my login functionality so that it returns the token in the response body as opposed to the headers.</p>
  <p>I have no idea how to do this, currently no JSON body object is returned, only the headers and I will have to change a lot of my AuthorizationFilter and AuthenticationFilter classes. If someone could point me in the right direction or advice me on what to change that'd be greatly appreciated.</p>
  <p>Thanks.</p>
  <p>AuthorizationFilter:</p>
  <pre><code>public class AuthorizationFilter extends BasicAuthenticationFilter {
  
  public AuthorizationFilter(AuthenticationManager authenticationManager) { super(authenticationManager);}
  
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
  
          throws IOException, ServletException {
  
          String header = request.getHeader(&quot;Authorization&quot;);
  
          if(header == null || !header.startsWith(&quot;Bearer&quot;)) {
  
          filterChain.doFilter(request,response);
  
          return;
          }
  
          UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(request);
  
          SecurityContextHolder.getContext().setAuthentication(authenticationToken);
  
          filterChain.doFilter(request,response);
  
          }
  
  
  private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
          String token = request.getHeader(&quot;Authorization&quot;);
          if(token != null) {
  
          String user = Jwts.parser().setSigningKey(&quot;SecretKeyToGenJWTs&quot;.getBytes())
          .parseClaimsJws(token.replace(&quot;Bearer&quot;,&quot;&quot;))
          .getBody()
          .getSubject();
  
          if(user != null) {
  
          return new UsernamePasswordAuthenticationToken(user, null, new ArrayList&lt;&gt;());
  
          }
          return null;
          }
          return null;
          }
  }
  </code></pre>
  <p>AuthenticationFilter:</p>
  <pre><code>   public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
  
          private AuthenticationManager authenticationManager;
  
          public AuthenticationFilter(AuthenticationManager authenticationManager) {
              this.authenticationManager = authenticationManager;
              setFilterProcessesUrl(&quot;/login&quot;);
          }
          @Override
  
          public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
              try {
  
                  com.example.gambit2.domain.User creds = new ObjectMapper().readValue(request.getInputStream(), com.example.gambit2.domain.User.class);
                  return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(creds.getUsername(), creds.getPassword(),new ArrayList&lt;&gt;()));
              }
  
          catch(IOException e) {
  
                  throw new RuntimeException(&quot;Could not read request&quot; + e);
              }
  
          }
          protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, Authentication authentication)
          {
              String token = Jwts.builder()
                      .setSubject(((User) authentication.getPrincipal()).getUsername())
                      .setExpiration(new Date(System.currentTimeMillis() + 864_000_000))
                      .signWith(SignatureAlgorithm.HS512, &quot;SecretKeyToGenJWTs&quot;.getBytes())
                      .compact();
              response.addHeader(&quot;Authorization&quot;,&quot;Bearer &quot; + token);
  
  
          }
      }
  </code></pre>
  <p>UserController's signup method:</p>
  <pre><code>@PostMapping(&quot;/signup&quot;)
          public void signUp(@RequestBody User user) {
                  user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
                  userRepository.save(user);
                  System.out.println(user.getUsername() + &quot; SAVED SUCCESSFULLY&quot;);
          }
  </code></pre>
  <p>REACT Home.js:</p>
  <pre><code>const SIGNUP_URL = 'http://localhost:8080/users/signup';
  const LOGIN_URL = 'http://localhost:8080/login';
  class Home extends Component {
  
      constructor(props) {
          super(props);
          this.state = {
              isAuthenticated:false,
              resData: ''
          };
      }
  
      componentDidMount() {
          const payload = {
              &quot;username&quot;: &quot;hikaru&quot;,
              &quot;password&quot;: &quot;JohnSmith72-&quot;
          };
          fetch(SIGNUP_URL, {
              method: 'POST',
              headers: {
                  &quot;Accept&quot;: &quot;application/json&quot;,
                  &quot;Content-Type&quot;: &quot;application/json&quot;
              },
              body: JSON.stringify(payload)
          })
              .then(response =&gt; response.json())
              .then((data) =&gt; {
                  console.log(data);
              });
          fetch(LOGIN_URL, {
              method: 'POST',
              headers: {
                  &quot;Accept&quot;: &quot;application/json&quot;,
                  &quot;Content-Type&quot;: &quot;application/json&quot;
              },
              body: JSON.stringify(payload)
          })
              .then(response =&gt;
  
                  console.log(response.headers.get(&quot;Authorization&quot;)
              );
  
      }
  </code></pre>
  <p>In the above fetch call the /signup is successful and it the server outputs 'Tim is saved successfully', and the login is also successful but the token is sent in response and the 'console.log(response.headers.get(&quot;Authorization&quot;)) returns 'null'.</p>
  <p>I am aware that with CORS fetch will not work for auth header as it can only be used for like 4 headers right?</p>
  <p>I tried to add a method that loops through each entry and prints them, and then call it in the .then() as such:</p>
  <pre><code>.then(response =&gt; this.iterateThroughEntries(response)
          );
  </code></pre>
  <p>But this only printed the default headers, not the auth header.</p>
  <p>Thanks</p>