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
Related
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.
i am trying to send a synchronized request to https server with esp8266 and i am using httpbin.org for testing purpose and i want to synchronize the requests. i mean how to not sending request until the previous is recieved and without using delay?
by comparing code (below) and result (below) you can see that httpsClient.readString() returns empty result from time to time. why? how to explain that? and how to fix that or get around it?
code and result are bellow. please help.
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
//i cut wifi ssid and pswrd declaration to shorten the question
const char *host = "httpbin.org"; //Domain to Server
String path = "/post"; //Path of Server
const int httpsPort = 443; //HTTPS PORT (default: 443)
WiFiClientSecure httpsClient;
String response;
void setup() {
//i cut wifi set up declaration to shorten the question
httpsClient.setInsecure();
if(httpsClient.connect(host, httpsPort)){
Serial.println("Connected to "+String(host));
}else
Serial.println("error connecting");
}
void loop() {
httpsClient.print(String("POST ") + "/response-headers" + " HTTP/1.1\r\n" +
"Host: " + "httpbin.com\r\n"+
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length: 13\r\n\r\n" +
"say=Hi&to=Sam\r\n");
while(httpsClient.available()) {
response = httpsClient.readStringUntil('\n');
Serial.println(response);
}
Serial.println("---------------------------------------------------------");
}
Result:
---------------------------------------------------------
HTTP/1.1 200 OK
Date: Wed, 26 May 2021 16:20:01 GMT
Content-Type: application/json
Content-Length: 68
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
{
"Content-Length": "68",
"Content-Type": "application/json"
}
---------------------------------------------------------
---------------------------------------------------------
HTTP/1.1 200 OK
Date: Wed, 26 May 2021 16:20:01 GMT
Content-Type: application/json
Content-Length: 68
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
{
"Content-Length": "68",
"Content-Type": "application/json"
}
HTTP/1.1 200 OK
Date: Wed, 26 May 2021 16:20:01 GMT
Content-Type: application/json
Content-Length: 68
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
{
"Content-Length": "68",
"Content-Type": "application/json"
}
---------------------------------------------------------
HTTP/1.1 200 OK
Date: Wed, 26 May 2021 16:20:02 GMT
Content-Type: application/json
Content-Length: 68
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
{
"Content-Length": "68",
"Content-Type": "application/json"
}
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
---------------------------------------------------------
HTTP/1.1 200 OK
Date: Wed, 26 May 2021 16:26:19 GMT
Content-Type: application/json
Content-Length: 68
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
{
"Content-Length": "68",
"Content-Type": "application/json"
}
and so on.....
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
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"); }
});
I'm trying to use the Microsoft Azure OCR API found here for a React Native app.
I can get the API to work fine on local images with Postman, but for some reason, I get an "Unsupported Media Type" when I try using fetch within my app.
I originally called the api with this code:
_analyzeImage = () => {
const { image } = this.state;
const url = 'https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/ocr';
const data = new FormData();
data.append(image);
fetch(url, {
method: 'post',
body: data,
headers: {
'Ocp-Apim-Subscription-Key': '***********************',
}
}).then(res => {
console.log(res)
});
}
Where image looks like:
That, when ran using the XCode simulator, yields:
And the response:
{
"code":"UnsupportedMediaType",
"requestId":"6ff43374-e5f9-4992-9657-82ec1e95b238",
"message": "Supported media types: application/octet-stream, multipart/form-data or application/json"
}
Weirdly, the content-type seemed to be test/plain. So, even though I thought that the FormData object was supposed to take care of content type, I tried adding 'content-type': 'multipart/form-data', but got the same response (although the content-type header in the network inspector did change to multipart/form-data.
I used create-react-native-app to set up the project, and want to to work on iOS and android. If anyone has any ideas - or any other ways to do OCR, if there's a better native solution - I'd appreciate it!
As stated in the doc page you link to, if you send
application/json, your payload must look like this:
{"url": "http://example.com/images/test.jpg"}
if application/octet-stream,
[Binary image data]
if multipart/form-data,
[Binary image data]
Right now you're not sending anything that matches expectations.
Example POST
The image,
Pass image by URL:
$ curl -v -X POST -H 'Ocp-Apim-Subscription-Key: 2exxxxxxxxxxxxxxxxxxxxxx' \
-H 'Content-type: application/json' \
--data-ascii '{ "url": "https://i.stack.imgur.com/RM7B3.png" }' \
https://westus.api.cognitive.microsoft.com/vision/v1.0/ocr
> POST /vision/v1.0/ocr HTTP/1.1
> Content-type: application/json
> Content-Length: 44
...
< HTTP/1.1 200 OK
< Content-Length: 196
< Content-Type: application/json; charset=utf-8
{
"language": "en",
...
"regions": [
{
...
"words": [
{
"boundingBox": "61,49,303,108",
"text": "hello."
}
...
or pass image by raw bytes:
$ curl -v -X POST -H 'Ocp-Apim-Subscription-Key: 2exxxxxxxxxxxxxxxxxxxxxx' \
-H 'Content-type: application/octet-stream' \
--data-binary #hello.png \
https://westus.api.cognitive.microsoft.com/vision/v1.0/ocr
> POST /vision/v1.0/ocr HTTP/1.1
> Content-type: application/octet-stream
> Content-Length: 11623
...
< HTTP/1.1 200 OK
< Content-Length: 196
< Content-Type: application/json; charset=utf-8
{
"language": "en",
...
"regions": [
{
...
"words": [
{
"boundingBox": "61,49,303,108",
"text": "hello."
}
...