Why in React, my axios API call has Authorization Header which contains Bearer <token> but not being authorized and gives 401 error - reactjs

I'm making axios call to my php API (which shows user data when a valid token is sent back to API server) and sending a valid jwt token in request header (along with Bearer as prefix) and in the Network's tab its showing that my token is being sent in the header but still it gives me 401 error and returns the Error msg of API that "jwt is empty"...
my API to fetch user data (when valid token is provided) is on http://localhost/Auth/api/validate.php
and client side is on http://localhost:3000
This API is in php and works perfectly fine on Postman. But gives me 401(unauthorized) when I call it in react. I searched this error and everyone says that u should have token in the Request header, I do have it but its not being read by the server and server considers it null so sends me unauthorized error. Please Please help me someone!!!!!
here is the axios API call:
e.preventDefault();
const token = localStorage.getItem("jwttoken");
axios.post('http://localhost/Auth/api/validate.php',token, {
headers: {
'Authorization' : 'Bearer '+token,
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
}} )
.then(response =>
{
console.log(response.data);
console.log(response);
return response;
})
.catch(error => {
if (error) {
console.log("Sorry.....Error"); }
});
Response Headers
> Request URL: http://localhost/Auth/api/validate.php
> Request Method: POST
> Remote Address: [::1]:80
> Status Code: 401 Unauthorized
> Referrer Policy: no-referrer-when-downgrade
> Accept: application/json; charset=UTF-8, */*
> Access-Control-Allow-Credentials: true
> Access-Control-Allow-Headers: Content-Type, Accept, X-Auth-Token, Origin, Authorization, Client-Security-Token, Accept-Encoding, X-Requested-With
> Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
> Access-Control-Allow-Origin: *
> Access-Control-Exposed-Header: true
> Authorization Access-Control-Max-Age: 33600
> Connection: Keep-Alive
> Content-Length: 34
> Content-Type: application/json; charset=UTF-8, */*
> Date: Sat, 23 Mar 2019 12:33:00 GMT Keep-Alive: timeout=5, max=99
> Server: Apache/2.4.29 (Win32) OpenSSL/1.1.0g PHP/7.2.3 X-Powered-By:
> PHP/7.2.3
Request Headers:
> Provisional headers are shown Accept: application/json, text/plain, */*
>Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7IlZlbmRvcklEIjoiNDQiLCJDb21wYW55TmFtZSI6IlRhZGEiLCJDb250YWN0UGVyc29uIjoiVGFkYSIsIkNvbnRhY3RObyI6Ijg3ODciLCJlbWFpbCI6InRhZGFAZ21haWwuY29tIn19.YmaD_VjMKYifWXd4DsRXRodVDpBy8zASLnIfgquCwLI
> Content-Type: application/json
> Origin: http://localhost:3000
> Referer: http://localhost:3000/profile
> User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36
> Request Payload: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7IlZlbmRvcklEIjoiNDQiLCJDb21wYW55TmFtZSI6IlRhZGEiLCJDb250YWN0UGVyc29uIjoiVGFkYSIsIkNvbnRhY3RObyI6Ijg3ODciLCJlbWFpbCI6InRhZGFAZ21haWwuY29tIn19.YmaD_VjMKYifWXd4DsRXRodVDpBy8zASLnIfgquCwLI
Here is my API validate.php
<?php
// required headers//
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json; charset=UTF-8, */*");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Max-Age: 33600");
header("Content-Length: 144");
header("Accept: application/json; charset=UTF-8, */*");
header("Access-Control-Exposed-Header: Authorization");
header("Access-Control-Allow-Headers: Content-Type, Accept, X-Auth-Token, Origin, Authorization, Client-Security-Token, Accept-Encoding, X-Requested-With");
// required to decode bbbb
include_once 'config/core.php';
include_once 'libs/php-jwt-master/php-jwt-master/src/BeforeValidException.php';
include_once 'libs/php-jwt-master/php-jwt-master/src/ExpiredException.php';
include_once 'libs/php-jwt-master/php-jwt-master/src/SignatureInvalidException.php';
include_once 'libs/php-jwt-master/php-jwt-master/src/JWT.php';
use \Firebase\JWT\JWT;
// get posted data
$data = json_decode(file_get_contents("php://input"));
// get jwt
$jwt=isset($data->jwt) ? $data->jwt : "";
// if jwt is not empty
if($jwt){
// if decode succeed, show user details
try {
// decode jwt
$decoded = JWT::decode($jwt, $key, array('HS256'));
// set response code
http_response_code(200);
// show user details
echo json_encode(array(
"message" => "Access granted.",
"data" => $decoded->data
));
}
// if decode fails, it means jwt is invalid
catch (Exception $e){
// set response code
http_response_code(401);
// tell the user access denied & show error message
echo json_encode(array(
"message" => "Access denied. Decode fails",
"error" => $e->getMessage()
));
}
}
// show error message if jwt is empty
//gggg
else{
// set response code
http_response_code(401);
// tell the user access denied
echo json_encode(array("message" => "Access denied. Empty"));
}
?>
EDIT
I also tried sending the token without 'Bearer' prefix but it didnt work. On Postman I send a post request (in the body) to my server API like this(which works fine):
{
"jwt": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7IlZlbmRvcklEIjoiNTkiLCJDb21wYW55TmFtZSI6IkVub3VnaCIsIkNvbnRhY3RQZXJzb24iOiJlbm91Z2giLCJDb250YWN0Tm8iOiIzNDM0NCIsImVtYWlsIjoiZUBnbWFpbC5jb20ifX0.o4V6zu8AFBAMoJgRe_jvMoByDK3yDEiF_pxW4ttqpYQ"
}

The php code is expecting JWT token in the body. The token should be in a JSON as shown below.
const token = localStorage.getItem("jwttoken");
axios.post('http://localhost/Auth/api/validate.php',{"jwt":token}, {
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
}} )
.then(response =>
{
console.log(response.data);
console.log(response);
return response;
})
.catch(error => {
if (error) {
console.log("Sorry.....Error"); }
});

Related

Jeresy CORS filter working but React rest GET failing still with header ‘access-control-allow-origin’ is not allowed

I create a rest react front end to talk to a Jersey servlet on tomcat on the back end for RH 8.6. When react tried to do on REST GET or POST commands I got the "‘access-control-allow-origin’ is not allowed according to header" error. So I then added the CORS filter which was suppose to fix the origin problem, but the react client is still failing. I have tried different filters but there is no change. I assume the problem is in the react GET fetch but it looks ok with me and gets a header back when mode: 'no-cors' is set. In the debugger the CORSFilter class gets the GET, but it does not reach the resource class endpoint so its getting rejected.
Using postman I have verified the CORSFilter is inserting the values in the response as you can see here.
POST http://localhost:8080/rtc-servlet/mcd/location
Headers from postman tool:
Status Code: 200
access-control-allow-credentials: true
access-control-allow-headers: X-Requested-With, CSRF-Token, X-Requested-By, Authorization, Content-Type
access-control-allow-methods: API, GET, POST, PUT, DELETE, OPTIONS, HEAD
access-control-allow-origin: *
access-control-max-age: 151200
connection: keep-alive
content-length: 701
content-type: application/json
date: Sat, 10 Dec 2022 02:52:19 GMT
keep-alive: timeout=20
servlet code:
#Provider
public class CORSFilter implements ContainerResponseFilter {
#Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
// *(allow from all servers) OR https://crunchify.com/
responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
// As part of the response to a request, which HTTP headers can be used during the actual request.
responseContext.getHeaders().add("Access-Control-Allow-Headers",
"X-Requested-With, CSRF-Token, X-Requested-By, Authorization, Content-Type");
Also tried these options:
"Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
responseContext.getHeaders().add("Access-Control-Allow-Methods",
"API, GET, POST, PUT, DELETE, OPTIONS, HEAD");
// How long the results of a request can be cached in a result cache.
responseContext.getHeaders().add("Access-Control-Max-Age", "151200");
}
}
#GET // read in updated/original files
#Produces(MediaType.APPLICATION_JSON) // what format we send back
public JsonObject getLocationValues() {
System.out.println("Called location getLocationValues ");
return locationRepository.readConfigFile(false);
}
React Rest GET fetch:
const urll1 = "http://localhost:8080/rtc-servlet/mcd/location";
useEffect(() => {
const fetchPost = async () => {
await fetch(urll1, {
// mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
"Accept": "application/json",
"Access-Control-Allow-Origin": "*",
},
})
.then((response) => {
if (response.ok) {
response.json().then(data => {
console.log("response fetchPost :" + JSON.stringify(data));
setPosts1(data);
});
} else {
console.log("response was not ok");
}
})
.catch((err) => {
console.log(err.message);
});
};
fetchPost();
}, []);
The console error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/rtc-servlet/mcd/location. (Reason: header ‘access-control-allow-origin’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/rtc-servlet/mcd/location. (Reason: CORS request did not succeed). Status code: (null).
NetworkError when attempting to fetch resource.
So does anyone see that I am doing wrong?
After read the CORS not working posts in stackoverflow again I came across a commit about getting the origin from the header and then setting Access-Control-Allow-Origin to it vs. "*" and react on port localhost:3000 started to get responses back from the localhost:8080 servlet (origin is being set to "localhost:3000"). This was the forum string if you want to read up on it:
How to enable Cross domain requests on JAX-RS web services?.
So the change in the filter class is as follows:
String origin = requestContext.getHeaderString("origin");
if ((origin != null) && (!origin.isEmpty())) {
headers.add("Access-Control-Allow-Origin", origin);
} else {
// *(allow from all servers) OR https://crunchify.com/
headers.add("Access-Control-Allow-Origin", "*");
}
headers.add("Access-Control-Allow-Credentials", "true");
and in the js script "Access-Control-Allow-Origin": "*" was deleted:
await fetch(urll1, {
headers: {
'Content-Type': 'application/json',
"Accept": "application/json"
},
})
I am not sure if I now need the else since "*" didn't work for me, but I left it in. If its not needed or I am just doing something that sort of works because I am using firefox please let me know.

400 Error while trying to call a PATCH API call in React even when the OPTIONS has passed OK

I have been trying to use React to make API calls, I am able to successfully run GET and POST requests but when i ran PATCH, it return 400 error which is bad request. But i am able to run the same request successfully on Postman.
I have a feeling I am not passing the data in the right format, but the body and the headers are being passed in the same form as in the POST method which is working fine.
Also, the preflight request is being passed as OK (200) but the connection closes at PATCH request
This is my request, where the Id is being received from another component which is then passed to the API.
class AddPatients extends React.Component {
constructor(props)
{
super(props);
this.state = {message :''};
console.log(this.props.list_id);
}
addPatients(url)
{
let xhr = new XMLHttpRequest();
xhr.open('PATCH',url, true);
xhr.setRequestHeader("Authorization", "Auth_key");
xhr.setRequestHeader("X-OHP-Developer-API-Key", "API_Key ");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
let body = {
data:
[
{
//record 1
},
{
//record 2
}
]
}
const res = xhr.send(JSON.stringify(body));
console.log('the response is', res);
}
onButtonClick()
{
var url = 'the url link/' + this.props.list_id;
this.addPatients(url);
}
render() {
return(
<div>
<button onClick={this.onButtonClick.bind(this)}> Add patients to the list </button>
{this.props.list_id}
</div>
);
}
}
export default AddPatients;
It has nothing to do with the OPTIONS request i think because it returns OPTIONS IN Allow-Methods options like:
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: 18.236.241.179:443
Referrer Policy: no-referrer-when-downgrade
HTTP/1.1 200 OK
Date: Tue, 31 Dec 2019 01:03:22 GMT
Server: Apache
Strict-Transport-Security: max-age=63072000; includeSubDomains
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,POST,HEAD,DELETE,PUT,OPTIONS,PATCH
Access-Control-Allow-Headers: authorization,x-requested-with,x-ohp-developer-api-key,content-type
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 336
Keep-Alive: timeout=15, max=98
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1
Sorry, I resolved it. Was passing wring syntax in the JSON body, stupid mistake.

Alexa Remainder API (REST API) - Invalid bearer token

I am trying to send the Alert/Remainder via POSTMan to my skill.
Option 1: Authentication token API with Scope "alexa:skill_messaging"
POST /auth/o2/token HTTP/1.1
Host: api.amazon.com
Content-Type: application/x-www-form-urlencoded
User-Agent: PostmanRuntime/7.20.1
Accept: */*
Cache-Control: no-cache
Postman-Token: 2ae7afa3-c3f8-493f-b6e3-2db1e44e3a17,a4e45e8e-d0eb-4b3f-a612-e7d1959fdbe6
Host: api.amazon.com
Accept-Encoding: gzip, deflate
Content-Length: 236
Connection: keep-alive
cache-control: no-cache
grant_type=client_credentials&client_id=******************&client_secret=***********17a4f7b348982bdb4&scope=alexa%3Askill_messaging
Screenshote:
option 2: Authentication token API with Scope "alexa::alerts:reminders:skill:readwrite"
POST /auth/o2/token HTTP/1.1
Host: api.amazon.com
Content-Type: application/x-www-form-urlencoded
User-Agent: PostmanRuntime/7.20.1
Accept: */*
Cache-Control: no-cache
Postman-Token: 2ae7afa3-c3f8-493f-b6e3-2db1e44e3a17,c6765f77-6e35-419f-b614-780dae20ad4e
Host: api.amazon.com
Accept-Encoding: gzip, deflate
Content-Length: 236
Connection: keep-alive
cache-control: no-cache
grant_type=client_credentials&client_id=**************************&client_secret=************************&scope=alexa%3A%3Aalerts%3Areminders%3Askill%3Areadwrite
Step 2: Submitting the Alert request using token generated by Scope "alexa:skill_messaging" getting Invalide Bearer token
Let me know if I am missing anything and also where can find different scope for Alexa Authenictaion Token API
Unfortunately,
"That's a limitation of the Reminders API - you need to use the in-session access token to create reminders. You can run GET, UPDATE and DELETE operations out of session as well, so check this out for more information."
Only speaking with the device is possible get in-session access token to create reminders.
Out-session - Get reminders created by the skill (Skill Messaging API):
const IncomingMessageHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'Messaging.MessageReceived'
},
async handle(handlerInput) {
const { requestEnvelope, context } = handlerInput;
console.log(`Message content: ${JSON.stringify(requestEnvelope.request.message)}`);
try {
const client = handlerInput.serviceClientFactory.getReminderManagementServiceClient();
const remindersResponse = await client.getReminders();
console.log(JSON.stringify(remindersResponse));
} catch (error) {
console.log(`error message: ${error.message}`);
console.log(`error stack: ${error.stack}`);
console.log(`error status code: ${error.statusCode}`);
console.log(`error response: ${error.response}`);
}
context.succeed();
}
}
https://developer.amazon.com/docs/smapi/alexa-reminders-api-reference.html#in-session-and-out-of-session-behavior-for-alexa-reminders-api
https://forums.developer.amazon.com/questions/196445/reminders-can-only-be-created-in-session.html#answer-196860
https://developer.amazon.com/pt-BR/docs/alexa/smapi/skill-messaging-api-reference.html

"Download Network Failed" - Chrome failes on 160kb tiff file in React Redux app

So I have been looking around. Obviously there's a fair amt of on the web about these "Download Network Failded" problems. I feel our problem is somewhat unique in that we have one file. a 160kb tiff file (really it's a blog that we append a tiff extension too). I just stumbled on this when testing. It's a random image on my machine. I have much bigger and smaller files that process fine through the app. When debugging, the response looks good in fiddler, like any other good response. Also tracking the response through our React app it looks good all the way through. So the problem happens somewhere in Chrome and just for this one file. We've tried all standard stuff found here.
https://productforums.google.com/forum/#!topic/chrome/7XBU6g6_Ktc
Mainly fiddling with extensions (disabling them), download locations, reinstalling, etc. But the idea that is one smaller jpg file we are sending for conversion (the app is a basic convertor) has me perplexed. Has anyone ever seen something like this??
So here is how we handle the file in our redux action.
WE use these packages
import dataURLtoBlob from 'dataurl-to-blob';
import FileSaver from 'file-saver';
And we have a dispatch function we pass in for a response in our thunk (the fetch)
export function saveFile(data, fileName) {
return (dispatch) => {
var ie = navigator.userAgent.match(/MSIE\s([\d.]+)/),
ie11 = navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/rv:11/),
ieEDGE = navigator.userAgent.match(/Edge/g),
ieVer = (ie ? ie[1] : (ie11 ? 11 : (ieEDGE ? 12 : -1)));
if (ie && ieVer < 10) {
console.log("No blobs on IE ver<10");
return;
}
var mimeType = data.split(',')[0].split(':')[1].split(';')[0];
var extension = '';
if (mimeType.includes("zip")) {
extension = "zip"
}
else {
extension = mimeType.substr(mimeType.lastIndexOf('/') + 1);
}
var npmBlob = dataURLtoBlob(data);
if (ieVer > -1) {
FileSaver.saveAs(npmBlob, fileName + "." + extension);
} else {
var downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
downloadLink.style.display = "none";
downloadLink.href = data;
downloadLink.download = fileName;
downloadLink.click();
}
}
}
Relevant part of the fetch itself
}).then(response => {
//debugger;
var responseObj = JSON.parse(response);
//handle multi-retrieve
if (targetExtension.includes("/File/Retrieve")) {
for (let array of responseObj) {
if (array.ReturnDocument) {
if (responseObj.length > 1) {
dispatch(saveFile(responseObj[0].ReturnDocument, "testFiles_download"));
} else {
dispatch(saveFile(responseObj[0].ReturnDocument, responseObj[0].ticketID));
}
}
}
}
var returnObject = { returnResult: responseObj, loading: false };
return callback(returnObject);
Everything looks good. http status codes are 200 and all other files are working. There is really nothing special about this jpg we send in as far as we can tell. And it looks good coming back.
Here is the request sent in:
POST http://redacted/api/File/Convert HTTP/1.1
Host: redacted-dev
Connection: keep-alive
Content-Length: 168078
Origin: http://redacted-dev
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryhgZddb45UOHBhsgs
Accept: */*
Referer: http://redacted-dev/ui/Convert
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Here is the raw response
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
Persistent-Auth: true
X-Powered-By: ASP.NET
Date: Tue, 02 Jan 2018 14:12:17 GMT
Content-Length: 3707173
Here is what the blob looks like when we get it back(abbreviated):
ReturnDocument=data:image/tiff;base64,SUkqAAg+............
You can file saver package to download a blob object.
Usage Example is as below:
// FileSaver Usage
import FileSaver from 'file-saver';
fetch('/records/download', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
}).then(function(response) {
return response.blob();
}).then(function(blob) {
FileSaver.saveAs(blob, 'fileName.zip');
})
One more way to download a file is that you make a get request which sends file from the server.
Then you can simply do the following:
window.open('full server link');
Then your file will get start downloading.

AngularJS: Refused to set unsafe header "Access-Control-Request-Headers"

I'm trying to call a REST API running locally using AngularJS. Here is the AngularJS code :
$http.defaults.headers.common = {"Access-Control-Request-Headers": "accept, origin, authorization"};
$http.defaults.headers.common['Authorization'] = 'Basic amF5M2RlYzpqYXk=';
$http({method: 'GET', url: 'http://127.0.0.1:5000/user/jay3dec'}).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
alert(data);
});
But I'm getting an errors in the browser console :
Refused to set unsafe header "Access-Control-Request-Headers"
I tried to query call the REST API running at http://127.0.0.1:5000/user/jay3dec using CURL.
curl -H "Origin: http://127.0.0.1:8000" -H "Authorization: Basic amF5M2RlYzpqYXk=" http://127.0.0.1:5000/user/jay3dec --verbose
And it gave the following output :
> GET /user/jay3dec HTTP/1.1
> User-Agent: curl/7.35.0
> Host: 127.0.0.1:5000
> Accept: */*
> Origin: http://127.0.0.1:8000
> Authorization: Basic amF5M2RlYzpqYXk=
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: application/json
< Content-Length: 454
< ETag: bff7b7db33baedb612276861e84faa8f7988efb1
< Last-Modified: Tue, 30 Dec 2014 14:32:31 GMT
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Headers: Authorization
< Access-Control-Allow-Methods: HEAD, OPTIONS, GET
< Access-Control-Allow-Max-Age: 21600
< Server: Eve/0.4 Werkzeug/0.9.6 Python/2.7.6
< Date: Sun, 25 Jan 2015 20:00:29 GMT
<
* Closing connection 0
{"username": "jay3dec", "_updated": "Tue, 30 Dec 2014 14:32:31 GMT", "password": "jay", "firstname": "jay", "lastname": "raj", "phone": "9895590754", "_links": {"self": {"href": "/user/54a2b77f691d721ee170579d", "title": "User"}, "parent": {"href": "", "title": "home"}, "collection": {"href": "/user", "title": "user"}}, "_created": "Tue, 30 Dec 2014 14:32:31 GMT", "_id": "54a2b77f691d721ee170579d", "_etag": "bff7b7db33baedb612276861e84faa8f7988efb1"}
Can any one spot what may be the issue ??
The code behind $http.defaults.headers.common is
var xhr = createXhr();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (isDefined(value)) {
xhr.setRequestHeader(key, value);
}
});
...
function createXhr() {
return new window.XMLHttpRequest();
}
Referring to XMLHttpRequest specification , browser will terminate if header is a case-insensitive match for one of the following headers
Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
...
That's why you can't use $http.defaults.headers.common to set Access-Control-Request-Headers header. Browser will handle request headers for you instead.
The problem is in CORS
You should make configure your server side to allow Authorization in header. I don't know what you are used for server but for my asp.net web api 2 server it look like:
Web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type,Authorization" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
......
For security reasons, browsers do not allow head has set some security risks, such as cookie, host, referer, etc. So, do not use the browser to parse the line head. It can be used on the server side set of agency sent.
Reference: Cross origin resource sharing

Resources