the request in postman works but in angular it doesn't - django

enter image description here
I send the bearer token returned by the login and it works
enter image description here
the token arrives but the api response is
Authentication credentials were not provided.

Had the same issue, solved it by passing a plain object, to the headers property like so!
return this.http.post('/test/hello',
formData,
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
}
);

Related

AWS API Gateway api returns request headers failed error

I am calling API using react.js application. I am getting error from AWS API Gateway about CORS policy:
Access to XMLHttpRequest at 'https://awsapigatewayid.execute-api.ap-south-1.amazonaws.com/staging/top10' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
From React App code for call api like:
let options = {
url: `https://awsapigatewayid.execute-api.ap-south-1.amazonaws.com/staging/top10`,
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Req-Time': getCurrentTimestamp(),
'Access-Control-Allow-Origin': '*',
},
data: data || {},
};
if (isAuthorised) {
options.headers['X-Auth-Token'] = 'usertokengoeshere';
}
const response = await axios(options);
My API from AWS API Gateway:
You need to remove the 'Access-Control-Allow-Origin': '*', from your API call, to solve your error, instead add it to your Lambda response. Preferably not with '*' but with your actual Origin.

How to send a POST request (registration) in Postman using pre-request script

I'm trying to create a new user using a pre-request script to be able to use a PUT request to edit user profile settings independently from other requests.
So I'm setting a token from the response to my env variable to use it in the header for the PUT request.
My whole pre-request script is not working - new user is not created and new token is not set. What am I missing?
const createUser = pm.environment.get('url') + 'users'
pm.sendRequest({
url: createUser,
method: 'POST',
header: {
'Content-type': 'application/json',
'X-Foo': 'bar'
},
body: {
mode: 'application/json',
raw: JSON.stringify({"user":{
"username":"{{$randomUserName}}",
"email":"{{$randomEmail}}",
"password": "Pa$$w0rd!"}
})
}
})
pm.sendRequest(function (err, response) {
pm.environment.set("tokenConduit", response.json().token);
});
I think this is incorrect:
body: {
mode: 'application/json',
raw: JSON.stringify({"user":{
"username":"{{$randomUserName}}",
"email":"{{$randomEmail}}",
"password": "Pa$$w0rd!"}
})
}
application/json goes into Headers like you have it, but the body is in raw format. See the example in Postman docs. You stringify a json, so it's just a bunch of charaters, mode "application/json" doesn't exist.
Another thing is you're sending 2 requests, but I think you want to send only one:
const request = {
url: createUser,
method: 'POST',
header: {
'Content-type': 'application/json',
'X-Foo': 'bar'
},
body: {
mode: 'application/json',
raw: JSON.stringify({"user":{
"username":"{{$randomUserName}}",
"email":"{{$randomEmail}}",
"password": "Pa$$w0rd!"}
})
}
};
pm.sendRequest(request, function (err, response) {
pm.environment.set("tokenConduit", response.json().token);
});
So you should have only one pm.sendRequest() in your code.
const createUser =
pm.sendRequest({
url: "https://reqres.in/api/users?page=2",
method: 'POST',
header: {
'Content-type': 'application/json',
'X-Foo': 'bar'
},
body: {
mode: 'application/json',
raw: pm.variables.replaceIn(JSON.stringify({"user":{
"username":"{{$randomUserName}}",
"email":"{{$randomEmail}}",
"password": "Pa$$w0rd!"}
}))
}
})
pm.sendRequest(function (err, response) {
pm.environment.set("tokenConduit", response.json().token);
});
you have to use pm.variables.replacein to use variables inside script section,
Goto console to see what was actually send:

AWS API Gateway working from POSTMAN, but not from AWS Lambda function

I have an API gateway, which is working from the POSTMAN, using a valid access token, but when I call the same API gateway from inside Lambda function, I am getting 403 access denied error for the same access token. I am not sure where I am missing something. It's really weird, where everything from URL, API_KEY, access token, JSON body is the same, but worked differently in both services.
Please let me know if you have some pointers.
Here is the function that I am using for calling API Gateway -
return new Promise((resolve, reject) => {
var options = {
'method': 'POST',
'url': 'https://XXXXXXXX.execute-api.ap-south-1.amazonaws.com/dev/Patient',
'headers': {
'Content-Type': 'application/json',
'X-Api-Key': 'XXXXXXXX',
'Authorization': 'Bearer ' + accessToken
},
body: JSON.stringify({"resourceType":"Patient","active":true,"name":[{"family":"Smith","given":["Emily"]}],"gender":"female","birthDate":"1995-09-24","identifier":["1221212121"],"managingOrganization":{"reference":"Organization/2.16.840.1.113883.19.5","display":"Good Health Clinic"}})
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
});
Thanks

AWS API Gateway working through CURL but not working through javascript

Hi I am trying to hit a AWS API gateway it's working fine on CURL but not working from JS
Brocking for CROS policy.
But from AWS I already enabled CROS
$.ajax({
url: ApiURL,
type: 'POST',
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(hash),
async: true,
crossDomain: true,
crossOrigin: false,
headers: {
'accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'POST'
},
CURL method hit through AJAX
$.ajax({
url: stripTrailingSlash(BASE_URL) + '/contact/send',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(body),
async: true,
headers: {
'X-CSRF-Token': csrfToken
},
My api gateway POST structure like this
My lambda response I did like this
const response = {
statusCode: statusCode,
headers:{ 'Access-Control-Allow-Origin' : '*' },
body: JSON.stringify({
message: responceMessage,
input: event,
}),
};
callback(null, response);
Error I am getting in my browser
It works in CURL because, CURL doesn't send OPTIONS request, but browser sends it whenever you are making a CORS request.
Response to the OPTIONS request is what browser uses to check whether you are allowed to call the API.
When you enable CORS in API Gateway, it will add the following headers
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'POST'
but if you enable Proxy Request Integration, API Gateway no longer modifies the response to add the headers. Hence, it won't work unless your lambda function adds these header by itself.

react native 0.50.3 authorization header not sent

I am using react-native 0.50.3 to send token authenticated requests to my backend and unfortunately the 'authorization' part of the header is not send by the fetch.
My code is the following :
async componentDidMount() {
var mytoken = await AsyncStorage.getItem('token');
fetch('http://myserver:8000/home', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Origin': '',
'Content-Type': 'application/json',
'authorization': 'Bearer ' + mytoken
}
})
.then((response) => response.json())
.then((content) => {
this.state.user = content.user;
})
.done();
}
And on my server side, the wireshark trace shows that the authorization is not in the request header :
Hypertext Transfer Protocol
GET /home/ HTTP/1.1\r\n
Host: 10.150.21.124:8000\r\n
Content-Type: application/json\r\n
Origin: \r\n
Accept: application/json\r\n
User-Agent: Expo/2.3.0.1012011 CFNetwork/893.14 Darwin/17.3.0\r\n
Accept-Language: en-us\r\n
Accept-Encoding: gzip, deflate\r\n
Connection: keep-alive\r\n
\r\n
[Full request URI: http://10.150.21.124:8000/home/]
[HTTP request 1/1]
[Response in frame: 2326]
And of course I get a 401 unhautorized by the server.
My backend is a django API with CORS installed and CORS_ORIGIN_ALLOW_ALL = True and ALLOWED_HOSTS = ['*'].
The versions of my developments framework elements are the following :
npm 4.6.1
node v9.3.0
react-native-cli 2.0.1
One important update, the request I try to do with react-native works like a charm with postman. So the issue is not located on the server side.
Thank you for your help.
Alex.
try with trailing slash, in url address:
fetch('http://myserver:8000/home/', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Origin': '',
'Content-Type': 'application/json',
'authorization': 'Bearer ' + mytoken
}
})
.then((response) => response.json())
.then((content) => {
this.state.user = content.user;
})
.done();
Pooya's answer worked for me by adding the trailing slash on the request object. Strange because it worked on postman without the trailing slash hence the challenge in debugging. P.S i am also using the same stack, django, django REST framework (DRF) react native
fetch('http://mywebsite.com/posts/', {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token
}
})