AWS post request works on postman but not react-native - amazon-web-services

This is my JS code for the API
export const getUser = async (user) => {
//Working
const json = await fetch( "*****/username/getUser", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
user:user
}),
})
.then((res) => {
return res.json();
})
.catch((err) => {
console.log("Error in getUser: " + err);
});
return json;
};
Here is an attempt to make the request, which unfortunately return the authentication error.
fetchUser.request("kirolosM")
.then((result)=>{
console.log(result);
}).catch((err)=>{console.log("Error ",err);})
The error
{
"message": "Missing Authentication Token"
}
I have tested the API using postman and it is working as expexted.

Probably useful to compare the request sent from your json code to the one you're sending from postman. It looks like you need to include you auth token in your headers in your request.
Something like
export const getUser = async (user) => {
//Working
const json = await fetch( "*****/username/getUser", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authentication": `Bearer ${token}`
},
...

Related

AWS Lambda Rerouting after Twitter Authorizing

I implemented a twitter login authorizer and I put an API route as the callback.
The Lambda function evoked on that route is the following:
const loginTwitterCallback = async (e, context) => {
const fetch = (...args) =>
import("node-fetch").then(({ default: fetch }) => fetch(...args));
const state = e.queryStringParameters.state;
const code = e.queryStringParameters.code;
try {
await fetch(
"https://api.twitter.com/2/oauth2/token?code=" +
code +
"&grant_type=authorization_code&client_id=" +
process.env.TWITTER_CLIENT_ID +
"&code_verifier=jwqoijoiw&redirect_uri=" + MY REDIRECT URI,
{
method: "POST",
headers: {
"Content-type": "application/x-www-form-urlencoded",
},
}
)
.then((res) => {
return res.json();
})
.then(async (data) => {
const accessToken = data.access_token;
return {
headers: {
Location:
"http://127.0.0.1:3000/auth/social?type=twitter&access_token=" +
encodeURIComponent(accessToken),
},
body: null,
statusCode: 302,
};
});
} catch (err) {
console.log(err);
}
};
Basically the user should be re-routed to the front-end where another POST request will be made to the API which will make a request to the Twitter API with the Bearer token and update the database.
The point is, I'm not being redirected to the front-end in the first place and I don't understand how to fix it.
Thanks a lot in advance.

React Native - Sending token to Django server

So I have this react native code that sends a token in string format, yes I've checked that var token = getAccessToken() is a string and I've console.log it to ensure it is a JWT token as well. But on the Django side when I check request.headers.get('Authorization', None) it outputs: 'Bearer [object Object]' what's going on?
React Native Code
import {Auth} from 'aws-amplify';
export async function getAccessToken() {
try {
const currentUser = await Auth.currentAuthenticatedUser();
console.log(currentUser);
Auth
.currentSession()
.then(res => {
let accessToken = res.getAccessToken();
// let jwt = accessToken.getJwtToken();
// You can print them to see the full objects
// console.log(`myAccessToken: ${JSON.stringify(accessToken)}`);
// console.log(`myJwt: ${JSON.stringify(jwt)}`);
console.log(accessToken.jwtToken)
return accessToken.jwtToken
});
} catch (error) {
console.log('error signing up:', error);
}
}
const getPosts = () => {
var token = getAccessToken();
const config = {
headers: { Authorization: `Bearer ` + token }
};
axios
.get(`${url}/posts`, config)
.then(response => {
console.log(response)
setData(response.data);
})
.catch(error => {
console.log(JSON.stringify(error));
});
}
I also tried
const config = {
headers: { Authorization: `Bearer ${token}` }
};
I also tried
function getPosts() {
var token = getAccessToken().then(token => {
const config = {
headers: {
Authorization: `Bearer ${token}`
}
};
console.log(token)
axios
.get(`${url}/posts`, config)
.then(response => {
console.log(response)
setData(response.data);
})
.catch(error => {
console.log(JSON.stringify(error));
});
}).catch(error => {
console.log(JSON.stringify(error));
});;
};
and console.log(token) is outputting "undefined"
Update getAccessToken to return result of
Auth .currentSession()
And
Make getPosts function async and await getAccessToken().
OR
Use the then block to result of promise
getAccessToken().then(token=>{ // Call the api },err=>{ // Handle the error }
Otherwise what you are getting is a promise that's not resolved yet.

django-rest-auth get username from rest-auth/user

I want to retrieve the user details for displaying the username of the user who is logged-in
I need to fetch the username from "http://127.0.0.1:8000/rest-auth/user/" from django-rest-auth
I am new to reactjs and tried the authentication which was successfully but couldn't get pass this.
I have tried this so far
axios.get(`http://127.0.0.1:8000/rest-auth/user/`,
{
headers: { 'Authorization': "token " + localStorage.getItem('token') }
}
).then(res => {
console.log(res)
}).catch(Error => {
console.log(Error)
})
which returns the forbidden 403 error;
Errors
Error: Request failed with status code 403
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)
Also in the above code I also specified the headers in the following manner headers: { 'Authorization': "token key_from_DRF " } but no luck
I have also tried this
axios.get(`http://127.0.0.1:8000/rest-auth/user/`,
{
headers: { 'Content-Type': 'application/json' }
}
)
.then(res => {
console.log(res)
}).catch(Error => {
console.log(Error)
})
which returns the same error as before.
How should I execute this request successfully?
The axios POST method is correct, however make sure you passes the token
let tokentoserver = localStorage.getItem('token');
console.log(tokentoserver);
axios.get(`http://127.0.0.1:8000/rest-auth/user/`,
{
headers: { 'Authorization': "Token " tokentoserver }
}
).then(res => {
console.log(res)
}).catch(Error => {
console.log(Error)
})
I have removed the + sign you used to add token together

loopback rest connection headers authorization

I'm trying to access the Shopify Orders API in a Loopback application. I have the following data source:
"ShopifyRestDataSource": {
"name": "ShopifyRestDataSource",
"connector": "rest",
"operations": [{
"template": {
"method": "GET",
"url": "https://mystore.myshopify.com/admin",
"headers": {
"accepts": "application/json",
"content-type": "application/json"
}
},
"headers": {
"Authorization": "Basic MzdiOD..."
},
"functions": {
"find": []
}
}]
}
And then I attempt a simple call:
var ds = app.dataSources.ShopifyRestDataSource;
ds.find(function(err, response, context) {
if (err) throw err;
if (response.error) {
next('> response error: ' + response.error.stack);
}
console.log(response);
next();
});
I'm getting the following exception message:
Error: {"errors":"[API] Invalid API key or access token (unrecognized login or wrong password)"}
at callback (/order-api/node_modules/loopback-connector-rest/lib/rest-builder.js:529:21)
The Shopify API authenticates by basic HTTP authentication and I'm sure my request works since the same data works with curl. What am I doing wrong?
I couldn't find the "Loopback way" to do this and I couldn't wait, so I just wrote a simple https Node call. I'll paste this in here but I won't accept it as the answer. I'm still hoping someone will provide the right answer.
let response;
const options = {
hostname: 'mystore.myshopify.com',
port: 443,
path: '/admin/orders.json',
method: 'GET',
auth: `${instance.api_key}:${instance.password}`
};
const req = https.request(options, (res) => {
res.setEncoding('utf8');
let body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
let jsonResponse = JSON.parse(body);
// application logic goes here
response = 'ok';
});
});
req.on('error', (e) => {
response = e.message;
});
req.end();

Trying to get then send a cookie using react and fetch

I've been trying to implement some authentication component in my app for a few hours now, and I still don't understand some of the things that are happening.
Basically, I'd like to send a POST request containing some credentials to my API, which sends me a cookie back with a token if the credentials worked. Then, the cookie should be included in the headers of all future requests to my API (which I believed was automatic).
server.js (my API is a mockup for now, with JSON files)
...
app.post('/api/login', jsonParser, (req, res) => {
fs.readFile(ACCOUNTS_FILE, (err, data) => {
if (err) {
console.error(err);
process.exit(1);
}
const accounts = JSON.parse(data);
const credentials = {
email: req.body.email,
password: req.body.password,
};
var token = null;
for (var i = 0; i < accounts.length; ++i) {
const account = accounts[i];
if (account.email === credentials.email
&& account.password === credentials.password) {
token = account.token;
break;
}
}
if (token) {
res.setHeader('Set-Cookie', `access_token=${token}; Secure; HttpOnly;`);
res.json({ token });
} else {
res.json({ token: null });
}
});
});
...
app.js
...
handleConnection(e) {
e.preventDefault();
const email = this.state.email.trim();
const password = this.state.password.trim();
if (!email && !password) {
return (false);
}
fetch(loginUrl, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
credentials: 'include',
},
body: JSON.stringify(this.state),
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.warn(error);
});
return (true);
}
...
Now the console.log(data) always displays my token (or null if my credentials are wrong), but the cookie thing doesn't work...
See, I receive the Set-Cookie header, but I still have no cookie on my page.
And even if I managed to get the cookie, when I try to create a cookie using document.cookie = "access_token=123"; and then send the request again, my cookie doesn't go in my header like it would with a jQuery Ajaxcall :
I read here that adding credentials: 'include' would save the day, but unfortunately it didn't.
What am I missing here?
Thanks in advance!
I had the same problem and I found the answer in Peter Bengtsson's comment here: https://davidwalsh.name/fetch
If I understood, in your case the fetch should be:
fetch(loginUrl, {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state),
})