Retrieve response header - authorization bearer token

jdallain
jdallain used Ask the Experts™
on
Hello Experts,

I'm trying to retrieve the authorization bearer token from the response header. In Chrome, I can see it in on the Network tab (see image), but I can't find it on the Console tab.

axios.post(`${ROOT_URL}/nosh/jwt/signin`,{ username, password }, config)
      .then(response => {    
             response.headers
             response.headers['autherization']
             response.headers['autherization:bearer']
             response.headers.valueOf('authorization') 
    })
      .catch(() => {       
      
      });
  }
}

Open in new window

I tried to console.log all the above. I can't figure out how to see/grab the token.

Thanks, James
bearer.PNG
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Dave BaldwinFixer of Problems
Most Valuable Expert 2014

Commented:
If that code sample is correct, then you're simply spelling 'Authorization' incorrectly as 'autherization'.  Note also that the names of the headers are capitalized in specific ways that you should copy.

Author

Commented:
Thanks for responding, Dave. I still get undefined.

James

console.log(response.headers['Authorization']);

Open in new window

Author

Commented:
Here's all the code. I'm getting the JWT on the Post.

import axios from 'axios';
import { browserHistory } from 'react-router';
import {
  AUTH_USER,
  UNAUTH_USER,
  AUTH_ERROR,
  FETCH_MESSAGE
} from './types';

const ROOT_URL = 'http://localhost:8088';
const base64 = require('base-64');


export function signinUser({ username, password }) {
  return function(dispatch) {
    // Submit email/password to the server
     var config = { 
          headers: {'Authorization' : 'Basic ' + base64.encode(username + ':' + password),
      }
    }

     axios.post(`${ROOT_URL}/nosh/jwt/signin`,{ username, password }, config)
      .then(response => {     
        dispatch({type:AUTH_USER});      
        console.log(response.headers['Authorization']);      
      })
      .catch(() => {
        dispatch(authError('Bad Login Info'));
      });
  }
}


export function authError(error){
  return{
    type: AUTH_ERROR,
    payload: error 
  }
}

Open in new window

11/26 Forrester Webinar: Savings for Enterprise

How can your organization benefit from savings just by replacing your legacy backup solutions with Acronis' #CyberProtection? Join Forrester's Joe Branca and Ryan Davis from Acronis live as they explain how you can too.

Dave BaldwinFixer of Problems
Most Valuable Expert 2014

Commented:
I'm not sure what you're doing.  Do you see any of the response headers in the 'console'?  In other words, does the method work at all?  Try it on a simple page that does not require a login.

Author

Commented:
Attached is:

console.log(response)
full_response.PNG

Author

Commented:
Attached is:

console.log(response.headers)
reponse_headers.PNG

Author

Commented:
Yeah, it's working. I can see it on the Network tab, but I can't grab it in code.
Dave BaldwinFixer of Problems
Most Valuable Expert 2014

Commented:
I don't know what to tell you except click on "Request Attention" in the little box with 3 dots to get someone else to look at this.

Author

Commented:
Ok, thanks for the effort.

James
leakim971Multitechnician
Top Expert 2014

Commented:
what do you get in Chrome console using this :
     axios.post(`${ROOT_URL}/nosh/jwt/signin`,{ username, password }, config)
      .then(function(response)  {     
        console.log(JSON.stringify(response));      
      })

Open in new window

Author

Commented:
{"data":"","status":204,"statusText":"No Content","headers":{},"config":{"transformRequest":{},"transformResponse":{},"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8","Authorization":"Basic amFtZXMuYWxsYWluQGdtYWlsLmNvbTpj"},"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"method":"post","url":"http://localhost:8088/nosh/jwt/signin","data":"{\"username\":\"james.allain@gmail.com\",\"password\":\"c\"}"},"request":{}}
leakim971Multitechnician
Top Expert 2014

Commented:
ok, so axios remove the header content, not sure why in your case.
I'm able to read my header with axios on my side.

so, just do a basic Ajax call to see if you get it, replace your code (what you post in your original question) by :
	var req = new XMLHttpRequest();
	req.open("POST", `${ROOT_URL}/nosh/jwt/signin`, true);
	req.onreadystatechange = function() {
		if(req.readyState == 4)
			console.log(req.getAllResponseHeaders());
			console.log(JSON.stringify(req.getAllResponseHeaders()));
	};
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.send(encodeURIComponent(username) + "=" + encodeURIComponent(password));

Open in new window


and please post what you get in console, I hope you will see the headers you're looking for...

Author

Commented:
Thanks. I'm getting a 401. I need to send...
var config = { 
          headers: {'Authorization' : 'Basic ' + base64.encode(username + ':' + password),
      }

Open in new window

...in the request header.

I tried...
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded",config);

Open in new window

...but I still got a 401.
leakim971Multitechnician
Top Expert 2014

Commented:
	var req = new XMLHttpRequest();
	req.open("POST", `${ROOT_URL}/nosh/jwt/signin`, true);
	req.onreadystatechange = function() {
		if(req.readyState == 4)
			console.log(req.getAllResponseHeaders());
			console.log(JSON.stringify(req.getAllResponseHeaders()));
	};
	req.setRequestHeader("Authorization", "Basic " + Base64.encode(username + ":" + password));
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.send(encodeURIComponent(username) + "=" + encodeURIComponent(password));

Open in new window

Author

Commented:
Got a 400.

Author

Commented:
The server is expecting a payload with username and password.
leakim971Multitechnician
Top Expert 2014

Commented:
Do you've a link to test it in live?
Let's try this :
	var req = new XMLHttpRequest();
	req.open("POST", `${ROOT_URL}/nosh/jwt/signin`, true);
	req.onreadystatechange = function() {
		if(req.readyState == 4)
			console.log(req.getAllResponseHeaders());
			console.log(JSON.stringify(req.getAllResponseHeaders()));
	};
	req.setRequestHeader("Authorization", "Basic " + Base64.encode(username + ":" + password));
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
	req.send(JSON.stringify({username:username, password:password}));

Open in new window

Author

Commented:
Test it live? I've never done that before

Author

Commented:
It doesn't seem to be doing anything with the added payload. It's like it locked up.
leakim971Multitechnician
Top Expert 2014

Commented:
Test it live? I've never done that before

I mean can I access to your site?

Author

Commented:
Definitely. Yes.
leakim971Multitechnician
Top Expert 2014

Commented:
nice, could you give me the address and a temporary account too?

Author

Commented:
I'm sorry. I'm still local. I thought you meant remote in.
leakim971Multitechnician
Top Expert 2014

Commented:
ok, let go back to your axios version, use this one : https://unpkg.com/axios@0.15.3/dist/axios.js
just update the source file adding the console after line 716 just like this :
	      var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; // line 716
	      console.log((typeof responseHeaders == "object")?JSON.stringify(responseHeaders):responseHeaders);

Open in new window


and let me know what you get in the console

Author

Commented:
I got a response. It's an empty "".

Author

Commented:
The non-axious version gave me a response of "".
leakim971Multitechnician
Top Expert 2014

Commented:
ok, let me know what the hacked axios show you please

Author

Commented:
Can I add that to my bundle.js? I can't find a axios.js file in node_modules that looks like that one. They're all really small files.

Author

Commented:
I found it

Author

Commented:
I got...

{"data":"","status":204,"statusText":"No Content","headers":{},"config":{"transformRequest":{},"transformResponse":{},"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8","Authorization":"Basic amFtZXMuYWxsYWluQGdtYWlsLmNvbTpj"},"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"method":"post","url":"http://localhost:8088/nosh/jwt/signin","data":"{\"username\":\"james.allain@gmail.com\",\"password\":\"c\"}"},"request":{}}

Author

Commented:
I'm getting a parseHeaders not defined in the axios.js
Multitechnician
Top Expert 2014
Commented:
ok, not sure about this error as you got the headers...
I'm assuming the browser don't set/send this header to the XMLHttpRequest object so the workaround would be to get it on the server side and send it back in the response, currently empty...

Author

Commented:
Cool. I'll work on that tomorrow. Thanks a lot for all your help. You really know your stuff. I'll let you know what I figure out

Author

Commented:
It wasn't being exposed on the server. Thanks a bunch for your help. I learned a lot. Wish I could give you more points :)

James

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial