Cors Issue In Ionic View - ionic2

Hello i have deployed my project in ionic view where i need to make a http call to remote server.I have implemented proxies like this
{
"name": "MobileUI",
"app_id": "608c237d",
"type": "ionic-angular",
"proxies": [
{
"path": "/Auth",
"proxyUrl": "https://example.com/Auth/Authenticate",
"rejectUnauthorized": false
}
]
}
And I make a login call to the from the provider like this
AuthenticateUser(username: string, password: string) {
var userNamePwd: any = {};
userNamePwd.username = username;
userNamePwd.password = password;
let body = JSON.stringify(userNamePwd);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('/Auth', body, options)
.map((res) => {
let data = this.extractData(res);
this.storage.set('id_token', data[0].Token);
this.sharedAuth.SetEntityData(data);
return data;
})
.catch(this.handleError);
}
The Login works perfectly when testing in web browser but when i upload the app in my ionic view i am getting this error response with status 0 for url null
I implemented the proxies in the way mentioned in http://blog.ionic.io/handling-cors-issues-in-ionic/ .
Am I missing something ?

the issue is that when you run the app in ionic view app, there is no local proxy to forward requests to your backend. So you get into cors issues because the local webview enforce strict cors in the ionic view app.
I hope the ionic team comes up with a fix. As for now, to my best knowledge, you should modify your backend to allow all origins, or use a web server as a proxy to forward your request to your api servers.

Related

AWS Amplify Multiple frontends single API & Backend

I have 2 amplify webapps and I want that both are using the same AWS backend. So i followed the instructions on https://docs.amplify.aws/cli/teams/multi-frontend/#workflow. App A has the full amplify backend src and App B shall use these too. So I run on App B.
amplify pull
>Amplify AppID found: df4xxxxxxx. Amplify App name is: XXXXX
>Backend environment dev found in Amplify Console app: XXXXX
Seems to work.
But when I now try to make an api call via:
AWS_API = 'api_name_on_aws';
async getUserInfosByUsername(username) {
var userInfos;
await API.get(this.AWS_API, `/users/infos/testuser`,
{
headers: {},
response: true,
body: {},
queryStringParameters: {},
})
.then((response) => {
userInfos = response;
})
.catch((error) => {
console.log(error.response);
});
return userInfos;
}
then no api request will send. (I can see within the google chrome dev console/network that no request is send).
The "request" method is just return "undefined" and thats all... On App A everything is working fine.
Did I miss something? Should I do something else that App B can use the API of APP A?

How do I verify the ID token with Firebase and Django Rest?

I just can't wrap my head around how the authentication is done if I use Firebase auth and I wish to connect it to my django rest backend.
I use the getIdTokenResult provided by firebase as such:
async login() {
this.error = null;
try {
const response = await firebase.auth().signInWithEmailAndPassword(this.email, this.password);
const token = await response.user.getIdTokenResult();
/*
No idea if this part below is correct
Should I create a custom django view for this part?
*/
fetch("/account/firebase/", {
method: "POST",
headers: {
"Content-Type": "application/json",
"HTTP_AUTHORIZATION": token.token,
},
body: JSON.stringify({ username: this.email, password: this.password }),
}).then((response) => response.json().then((data) => console.log(data)));
} catch (error) {
this.error = error;
}
},
The only thing I find in the firebase docs is this lackluster two line snippet: https://firebase.google.com/docs/auth/admin/verify-id-tokens#web
where they write
decoded_token = auth.verify_id_token(id_token)
uid = decoded_token['uid']
# wtf, where does this go?
# what do I do with this? Do I put it in a django View?
I found a guide here that connects django rest to firebase: https://www.oscaralsing.com/firebase-authentication-in-django/
But I still don't understand how its all tied together. When am I supposed to call this FirebaseAuthentication. Whenever I try to call the login function I just get a 403 CSRF verification failed. Request aborted.
This whole FirebaseAuthentication class provided by the guide I linked to above - should I add that as a path on the backend?
path("firebase/", FirebaseAuthentication, name="api-firebase"),
Which is the api endpoint my frontend calls?

Fetch Data from REST API sends two requests and can't authenticate

I'm trying to fetch data in my React app from an Django server with Django Rest Framework, I'm using the built in token authentication.
componentDidMount() {
let headers = {
"content-type": "application/json",
"authorization": "Token <token is here>"
};
fetch('http://localhost:8000/api/stats/', {
headers: headers,
})
.then(res => res.json())
.then((data) => {
this.setState({ games: data })
})
.catch(console.log)
}
Inspecting the page in Chrome reveals this
This looks like two separate requests but I'm not sure.
The requests that has status (failed) has the headers I provided in React with in it. This request seems to have failed completely, it did not even reach the server.
The other request that has the status 401 doesn't have the headers I provided. The request did however get a response from the server.
Anyone have an idea what's wrong?
Solved by David Nováks comment:
Installed django-cors-headers in my django project.
Added my React servers hosting address to CORS_ORIGIN_WHITELIST.

2 docker containers (Django & React), isomorphic-fetch and a login request

My setup is running on Docker with a frontend (React) as well as a backend (Django) container.
I'm using the login-form component of the drf-react-app below in another project and am clueless as to how the api fetch request in the loginUser action creator (src/actions/user.js) knows which URL it is supposed to use..?
user.js:22 POST http://localhost:3000/api/obtain-auth-token/ 404 (Not Found)
I want it to send the request to the server at port 8000. I took the code from this drf-react boilerplate: https://github.com/moritz91/drf-react-login
export function loginUser(username, password) {
return (dispatch, getState) => {
const payload = {username, password};
dispatch({type: LOGIN_USER_REQUEST, payload});
return fetch(`/api/obtain-auth-token/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload)
})
.then(handleResponse(dispatch, LOGIN_USER_RESPONSE))
.then((json) => {
saveUser(json);
return json;
})
.catch(handleError(dispatch, LOGIN_USER_RESPONSE))
}
}
What am I missing?
In your package.json you have a proxy property set to "http://backend:8000". The proxy is used to redirect requests to a given url when you make a request against your local server http://localhost:3000. So if that's not working then you might be missing a step that enables the proxy.

Making Network Requests through React Native

I have just started learning React Native. Built my Component and am trying to use an authenticate function written in a separate file to authenticate.
My Authenticate file looks like
var constants = require("../constants")
module.exports = function(usr,pwd){
var trailing_url = '/api/token/';
var url = constants.DOMAIN + trailing_url;
console.log("url");
return fetch(url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: usr,
password: pwd,
})
}).then(function(response){
return response.json();
}).then(function(json){
return json;
});
}
I am experiencing this error once i go to fetch. I am unable to make network requests to my backend in django which is running at http://127.0.0.1:8000/api/token/
I am getting the following error. Couldn't copy paste that here for some reason.
Another question I had is how to debug the code? I tried the Chrome debugger.
But its showing
Status: Waiting, press Ctrl R in simulator to reload and connect.
Tried refreshing the Simulator but didn't work.
Thanks Ashutosh for pointing that out. I didn't notice that since the emulator is a different machine, it wouldn't actually recognize localhost or 127.0.0.1
The problem was i was using the local machine's Loopback IP Address when requesting for data.