React-native / AWS API Gateway android issue - android

I am trying to use react-native with aws api gateway. Same code ( pure JS ) works great on ios but on android it fails with 403 error.
var signedRequest={
"headers": {
"Content-Type": "application/json",
"Accept": "application/json",
"x-amz-date": "20170918T134411Z",
"Authorization": "AWS4-HMAC-SHA256 Credential=ASIAIBC7RQ7MFUIRO7QQ/20170918/ap-northeast-1/execute-api/aws4_request, SignedHeaders=accept;content-type;host;x-amz-date, Signature=9fb6d4d4820024097f25aaa70648fxxx7a54a2db1a67d173189693dc073d0a0bac8",
"x-amz-security-token": "AgoGb3JpZ2luEKn////////xxxG1iKJBHjjvZH0DxcSqE889Wb3Mv+8PwMqrRe/O5dFFmP+9bQj+fSwVIUvmBplKkQB62x/xTelGHoCEOPXpBWLjT2OAUaBXOti7UZyfyMNgg56/Z58yxk4o2/37xPLbhXfODaL8kydFV8IaPJjdbJIX+a0kXycPLBnVIBdukUp9cMVD27mWN41u3w0VP5J8YiMPzrDnwKtb0U37naoIaknMBqNBDkMGQyHal/TBJ3wjJvJWVntrJvex0QKD8rDLHjaoiIYjBd+a04m2pKsBQJ9WQl02TTCPgRp0bb1oARF2hz0Xpi45Ba6a6E9SAL07UcRShTwX6rmxi0dZ38mkSbBMjI45Xg8r/VaRZx6/OyCq3u+nq4bgLCOMKqb/80F"
},
"data": "{\"data\":{\"func\":\"checkIfFacebookSignupComplete\",\"data\":{}}}",
"method": "POST",
"url": "https://xxx.execute-api.ap-northeast-1.amazonaws.com/dev/user/user"
}
var apiResponse=await fetch(signedRequest.url, {
method: signedRequest.method,
body: signedRequest.data,
headers: signedRequest.headers,
})
console.log("Got api response : ", apiResponse)
On iOS it receives a http response 200. However, on android it fails with:
"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
The Canonical String for this request should have been
'POST
/dev/user/user
accept:application/json
content-type:application/json; charset=utf-8
host:uihw7hnkn7.execute-api.ap-northeast-1.amazonaws.com
x-amz-date:20170918T134411Z
accept;content-type;host;x-amz-date
6b83b80f2875c2425c28b258886ad98603fd802095e35303a3c2a72528374fb5'
The String-to-Sign should have been
'AWS4-HMAC-SHA256
20170918T134411Z
20170918/ap-northeast-1/execute-api/aws4_request
008853cdfba53255257d9169e1a9c05500d01299da9efd4695ac8c66cb31e5e7'
"
I have tried axios as well . and same result. ( ios works fine, android fails ) I am using react-native 0.42.3.
Anyone got any idea what might be the issue?

After digging around a lot it appears the issue is related to as described here: https://github.com/facebook/react-native/issues/14445 . android okHttp library ( inernally used by react-native ) added charset=utf=8 to the request. So the solution is to calculate sig4 value with header like this:
var signedRequest={
"headers": {
"Content-Type": "pplication/json; charset=utf-8",
"Accept": "application/json",
"x-amz-date": "20170918T134411Z",
"Authorization": "Calculated sig4 auth",
"x-amz-security-token": "AgoGb3JpZ2luEKn////////xxxG1iKJBHjjvZH0DxcSqE889Wb3Mv+8PwMqrRe/O5dFFmP+9bQj+fSwVIUvmBplKkQB62x/xTelGHoCEOPXpBWLjT2OAUaBXOti7UZyfyMNgg56/Z58yxk4o2/37xPLbhXfODaL8kydFV8IaPJjdbJIX+a0kXycPLBnVIBdukUp9cMVD27mWN41u3w0VP5J8YiMPzrDnwKtb0U37naoIaknMBqNBDkMGQyHal/TBJ3wjJvJWVntrJvex0QKD8rDLHjaoiIYjBd+a04m2pKsBQJ9WQl02TTCPgRp0bb1oARF2hz0Xpi45Ba6a6E9SAL07UcRShTwX6rmxi0dZ38mkSbBMjI45Xg8r/VaRZx6/OyCq3u+nq4bgLCOMKqb/80F"
},
"data": "{\"data\":{\"func\":\"checkIfFacebookSignupComplete\",\"data\":{}}}",
"method": "POST",
"url": "https://xxx.execute-api.ap-northeast-1.amazonaws.com/dev/user/user"
}

The new AWS Amplify library (https://github.com/aws/aws-amplify) on the official AWS repo has support for automatic signing to API Gateway. This is part of the API module: https://github.com/aws/aws-amplify/blob/master/media/api_guide.md
You would first install the React Native npm module:
npm install aws-amplify-react-native
Then link the project: https://github.com/aws/aws-amplify/blob/master/media/quick_start.md#react-native-development
After that you can configure APIs:
import Amplify, { API } from 'aws-amplify';
Amplify.configure(
Auth: {
identityPoolId: 'XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab', //REQUIRED - Amazon Cognito Identity Pool ID
region: 'XX-XXXX-X', // REQUIRED - Amazon Cognito Region
userPoolId: 'XX-XXXX-X_abcd1234', //OPTIONAL - Amazon Cognito User Pool ID
userPoolWebClientId: 'XX-XXXX-X_abcd1234', //OPTIONAL - Amazon Cognito Web Client ID
},
API: {
endpoints: [
{
name: "ApiName1",
endpoint: "https://1234567890-abcdefgh.amazonaws.com"
},
{
name: "ApiName2",
endpoint: "https://1234567890-abcdefghijkl.amazonaws.com"
}
]
}
});
Following that your API Gateway requests are signed using the user's credentials:
let apiName = 'MyApiName';
let path = '/path';
let myInit = { // OPTIONAL
headers: {} // OPTIONAL
}
API.get(apiName, path, myInit).then(response => {
// Add your code here
});

I was fighting with the same issue. GET worked on both platforms, but POST only on iOS. Setting Content-Type to "application/json; charset=utf-8" before signing the request with sigV4Client fixed it for me.
const path = 'https://your-aws-endpoint.com';
const method = 'POST';
const queryParams = {};
const body = {};
const headers = {
'Content-Type' = 'application/json; charset=utf-8';
};
const client = sigV4Client.newClient({
accessKey: ACCESS_KEY,
secretKey: SECRET_ACCESS_KEY,
sessionToken: SESSION_TOKEN,
region: REGION,
endpoint: ENDPOINT,
});
const signedRequest = client.signRequest({
method: method,
path: path,
headers: headers,
queryParams: queryParams,
body: body
});
fetch(signedRequest.url, {
method: method,
headers: signedRequest.headers,
body: JSON.stringify(body)
}).then((results) => {
...
});

Related

How to add headers in login.vue?

How to update headers of apolloProvider?
Please check out nativescript-vue app repo:
https://github.com/kaanguru/vue-apollo-login
I can not explain properly so please check out the app. I don't know how to update appolloClient headers.
App repo has it's own comments and directives. It's easy to install and see by your self.
Current Structure of code:
Post request submits the user's identifier and password credentials for authentication and gets token in login page.
Apollo needs to place the jwt token into an Authorization header.
Main.js: Start apollo client if there is JWT start with headers
Goto login if there is no JWT
Goto birds list if there is JWT
Login : get jwt from server and write it to local storage
Go to birds list (does not show data because apollo initilised in main js)
import ApolloClient from 'apollo-boost'
import VueApollo from 'vue-apollo'
Vue.use(VueApollo)
const apolloClient = new ApolloClient({
uri: 'http://sebapi.com/graphql',
// HEADERS WORK FINE IF TOKEN WAS IN MAIN
// headers: {
// authorization: `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTg2MzU2NzM2LCJleHAiOjE1ODg5NDg3MzZ9.wpyhPTWuqxrDgezDXJqIOaAIaocpM8Ehd3BhQUWKK5Q`,
// }
})
const apolloProvider = new VueApollo({
defaultClient: apolloClient,
})
LOGIN.VUE
.then(
(response) => {
const result = response.content.toJSON();
console.log("Result from Server: ", result);
const token = result.jwt;
// HOW TO ADD HEADERS TO APOLLOCLIENT this.$apollo.provider.defaultClient
// this.$apollo.provider.defaultClient({
// request: (operation) => {
// operation.setContext({
// headers: {
// authorization: `Bearer ${result.jwt}` ,
// },
// });
// },
// });
},
Thank you for your interest.
NOTE: Please comment for more details. sebapi.com backend is a strapi graphql server.
Related Docs:
Apollo authentication
Apollo link composition
Vue apolloProvider Usage
The thing is you need to use ApolloLink in order to use it for all the requests. The way you're using won't work.
You have to use middleware apollo-link-context to achieve this.
As per Apollo-link-context docs
apollo-link-context: Used to set a context on your operation, which is used by other links further down the chain.
The setContext function takes a function that returns either an object or a promise that returns an object to set the new context of a request.
Add the below code to app.js and modify some changes and check.
import { setContext } from 'apollo-link-context'
const authLink = setContext((_, { headers }) => {
// get the authentication token from ApplicationSettings if it exists
const token = ApplicationSettings.getString("token");
// return the headers to the context so HTTP link can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : null
}
}
})
// update apollo client as below
const apolloClient = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache() // If you want to use then
})
Change in Login.vue
.then(
(response) => {
const result = response.content.toJSON();
console.log("Result from Server: ", result);
const token = result.jwt;
// Set token using setString
ApplicationSettings.setString("token", result.jwt);
},
Hope this helps!

Laravel API Rest doesn't work in device Android

I have an app in IONIC and in browser the call to API works but when I run on android device it shows this error:
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://192.168.1.***:8080/api/auth/login", ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://192.168.1.***:8080/api/auth/login: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "http://192.168.1.***:8080/api/auth/login"
__proto__: HttpResponseBase
In IONIC I send like API_URL = 'http://192.168.1.***:8080/api/'; to use HttpClient, and in Laravel I run php artisan serve --host 192.168.1.*** --port 8080
Please, someone knows what I should do to work?
The issue is related to CORS. You don't have to do anything to your IONIC app. You can enable CORS request by adding required headers for that you can create your own middleware in Laravel to handle cors, A sample middleware would be:
namespace App\Http\Middleware;
use Closure;
class Cors
{
public function handle($request, Closure $next)
{
return $next($request)->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', '*');
}
}
Then use it, by editing app\Http\Kernel.php
protected $middlewareGroups = [
'web' => [
// middleware for your web routes
],
'api' => [
'throttle:60,1',
'bindings',
'cors',
],
]
protected $routeMiddleware = [
// other middleware code
'cors' => \EuroKids\Http\Middleware\Cors::class,
]
You can customize the above middleware as required.
However, if you don't want to do create your own middleware you can use this library:
https://github.com/barryvdh/laravel-cors

axios post request working in React Native ios but not in android

I know there many answers regarding to this question but I can't seem to find one that works for me. I'm sending a post request to my server using axios but it does not work in android although it does in ios. I'm currently using server ip address (not localhost), and I'm also sending headers when request but it is still not going through the network request for android.
import axios from 'axios';
const SERVER_URL = 'http://serverip:3000';
export function signin({ username, password }) {
return function(dispatch) {
axios.post(`${SERVER_URL}/user/authenticate`, { username, password }, { headers: { 'Content-Type': 'application/json' } })
.then((response) => {
console.log('login response', response);
dispatch({
type: USER_AUTH,
});
AsyncStorage.setItem('token', response.data.token || '');
})
.catch((response) => console.log('user sign in err', response));
};
}
Has anyone had similar issue like myself and know how to make this work?
Thank you,
Set header to
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},

Cloud Function Not Working

I want to add notifications to an online android chatting app I have made. I am new to cloud functions, so I tried using the code given here https://firebase.googleblog.com/2016/08/sending-notifications-between-android.html
My index.js file
var firebase = require('firebase-admin');
var request = require('request');
var API_KEY = "xyz"; // Your Firebase
Cloud Messaging Server API key
// Fetch the service account key JSON file contents
var serviceAccount = require("firebase.json");
// Initialize the app with a service account, granting admin privileges
firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: "https://firebaseio.com/"
});
ref = firebase.database().ref();
function listenForNotificationRequests() {
var requests = ref.child('notificationRequests');
requests.on('child_added', function(requestSnapshot) {
var request = requestSnapshot.val();
sendNotificationToUser(
request.username,
request.message,
function() {
console.log('notificationrecived, sent and removed- ' +
request.username + ' '+ request.message,);
requestSnapshot.ref.remove();
}
);
}, function(error) {
console.error(error);
});
};
function sendNotificationToUser(username, message, onSuccess) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key='+API_KEY
},
body: JSON.stringify({
notification: {
title: message
},
to : '/topics/'+username
})
}, function(error, response, body) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '
+response.statusMessage);
}
else {n
onSuccess();
}
});
}
// start listening
listenForNotificationRequests();
I have successfully deployed this code to the server using node.js command line.
But this does not show up on the console and nor the logs that I added to debug
and the code doesn't seem to work. I have done everything given in the link i mentioned. I could use some help on how to fix my code
I don't know how big of a difference this makes, but in the Firebase admin set up page https://firebase.google.com/docs/admin/setup, it is mentioned that for Cloud Functions, the following line is sufficient for initialisation:-
var firebase = require('firebase-admin');
firebase.initializeApp(functions.config().firebase);
So, if you're going by the book, you may replace the initialisation line in your code with the one above and try running it again.
I didn't export my function listenForNotificationRequests() but called it only once at the end of the script.
Which is why it didn't show up on the Firebase Console.
I fixed this by simply exporting the function like this
exports.sendFollowerNotification = listenForNotificationRequests;

Including csrf token in a post request from react-native app

I have a react native app that posts and gets data from a remote server. In post, i need to include csrf token to avoid token mismatch errors. This is the backend laravel method
//Android Login
public function androidLogin(){
return response()->json([
'name' => 'Android Login',
'route' => 'androidLogin'
]);
}
This is the react native code(i have stripped out error catching code).
async handleSubmit(){
var me = this.state.message;
console.log('this connected',me);
let response = await fetch('http://not-brusselus.be/androidLogin', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN':'csrf_field()'
},
body: JSON.stringify({
session:{
email: 'chesterfield#gmail.com',
password: '123456',
}
})
});
//let res = await response.text();
if (true) {
console.log(response);
} else {
//Handle error
//let error = res;
//throw error;
}
}
The response shows laravel's token mismatch page. How can i send the csrf token successfully?.
Hang the CSRF token off of the window as defined in your main laravel layout file:
window.Laravel = {
csrfToken: '{{csrf_token()}}'
}
Then just use that in your javascript requests:
...window.Laravel.csrfToken
Edit
To the downvoter: This is literally how Laravel does it out of the box and recommends you do it as well.

Categories

Resources