csrf issue in fetch API call from react native - react-native

I am using the following code from react-native mobile application to make a social authentication call to dj-rest-auth local link. However my Facebook authentication succeeds each time and then the fetch (or axios) local API call executes, which runs perfectly for the first time/run returning me the token but thereafter on every other runs, it gives me an error saying missing or invalid csrf token. I can't used the Django docs getCookie function as it gives Document error since this is a react-native mobile application. Please guide how to properly have API calls using csrf from the mobile app, with the code being used below (which is inside an async function):
fetch(
"http://192.168.1.102:8080/dj-rest-auth/facebook/",
{
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type':'application/json',
},
xsrfCookieName:"csrftoken",
xsrfHeaderName:'X-CSRFToken',
body:JSON.stringify({access_token:resolvedToken})
}
)
.then(resp => resp.json())
.then(data => {
console.log(data);
}
)
.catch(error => console.log(error))
The logout function also give the missing or invalid csrf error, which is written below for reference:
async function Logout() {
fetch(
"http://192.168.1.102:8080/dj-rest-auth/logout/",
{
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type':'application/json',
},
xsrfCookieName:"csrftoken",
xsrfHeaderName:'X-CSRFToken'
}
)
.then(resp => resp.json())
.then(data => {console.log(data)})
.catch(error => console.log(error))
}

The issue above is resolved by removing "Session Authentication" from your default REST authentication classes in settings.py and keeping the "Basic Authentication" and "Token Authentication" enabled.
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
Source: https://github.com/Tivix/django-rest-auth/issues/164#issuecomment-860204677

Related

How to access HttpContext.Session from NextJs

Am using Nextjs for front end and Asp.Net core as a backend (API). I use JWT authentication to access the endpoints from Next Js using axios. Am also setting sessions on the backend to store user data. The problem is that HttpContext.Session is always null. The following is a sample of code I use:
axios.post(`https://localhost:44301/Home/GetValues`, { },
{
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
withCredentials: true
}
)
.then(res => {
console.log("Values", res.data);
})
.catch(err => console.log(err));
With Postman am able to access the HttpContext.Session. That means the Nextjs is not sending session cookies set by the Asp.net core.

Getting issue on API call where I am returning response like Unauthorized

I am trying to call an api using axios. The required params, headers I am passing correctly but on api hit I am returning response as api error: {"message":"Unauthorized"}. I tried with too many solutions like using bearer, jwt token, I also changed API calling library to fetch but still no success.
axiosGetWithHeaders('url',
{
param1: 'emailid'
},{
Authorization : 'token',
ContentType: 'application/json',
}
).then((res) => {
console.log("RESPONSE", JSON.stringify(res))
})
.catch((error) => {
console.error('api error: ' + JSON.stringify(error));
console.error('api error: ' + JSON.stringify(error.response.data));
});
Try with axios:
axios.defaults.headers.common["Authorization"] = accessToken;`enter code here`

React Native - Can't get data from asp.net web api

I'm building an app using React Native with Expo and an ASP.Net Web API.
I'm using two computers: one I published the Web API on it and using it as a server which has the IP 192.168.1.9 ,
and the other one with IP 192.168.1.6 I'm using for developing.
The problem is when I ping the server computer I get a reply and when I use postman I get the data I requested,
but when I run the app using Expo on my Android Phone, the request enters the catch and returns an error.
Here is the code:
var url = 'http://192.168.1.9/trainlast/api/Login';
fetch(url,
{
method: 'GET',
})
.then(response => { response.json(); })
.then(users => {
this.setState({ allUsers: users });
})
.catch(error => console.error('Error getting users :: ', error));
I have tried everything I could possibly think of, but no use.
Can someone tell me what the problem is? thank you .
You can configure Accept and Content-Type of headers.
And get the correct value for the object.
var url = 'http://192.168.1.9/trainlast/api/Login';
fetch(url,
{
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
})
.then((response) => response.json())
.then(res => {
this.setState({ allUsers: res.Username });
})
.catch(error => console.error('Error getting users :: ', error));

how to use axios to send data to line notify

I tried to send data to line notify server by axios and it fail
I have tried 2 version of code. as shown below
version 1 :
axios({
method: "post",
url: "https://notify-api.line.me/api/notify",
data: 'message="from vue"',
config: {
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "multipart/form-data"
}
},
Authorization: "Bearer [my token]"
})
.then(function(response) {
console.log(response);
})
.catch(function(response) {
console.log(response);
});
response is
XMLHttpRequest cannot load https://notify-api.line.me/api/notify due to access control checks.
Error: Network Error
and version 2 is :
axios
.post("https://notify-api.line.me/api/notify", "message=from vue", {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: "Bearer [my token]"
}
})
.then(response => {
console.log(response);
});
response is
Preflight response is not successful
XMLHttpRequest cannot load https://notify-api.line.me/api/notify due to access control checks.
Error: Network Error
What wrong with is
but I have tried in postman it work fine
Oh I am too familiar with this. Heres an explanation on stackoverflow as to why your request works with postman but not in browser. Long story short browsers send a preflight options check that will ask the server if the action you're about to perform is allowed. Postman does not. Usually the "Access-Control-Allow-Origin": "*" header is sent by the server to the browser not the other way around.
Inside the docs for LINE Notify you can find:
POST https://notify-api.line.me/api/notify
Sends notifications to users or groups that are related to an access token.
If this API receives a status code 401 when called, the access token will be deactivated on LINE Notify (disabled by the user in most cases). Connected services will also delete the connection information.
Requests use POST method with application/x-www-form-urlencoded (Identical to the default HTML form transfer type).
My guess is that your access_token might have been deactivated. Try requiring a new access token and doing the request again.
I think it is impossible to connect directly to the external url for the axios cuz ajax is basically for the inner data network. But you might have a controller if you do a web project, so you can just use your controller language to make a connection with line notify. In my case, I made a rails project and used axios in the vue.js, so I made a link like this.
View(axios) => Controller(Ruby) => LineAPI
me currently work on this too.
I did my app with node js.
My way below is for your reference, it works well.
const axios = require('axios');
const querystring = require('querystring');
axios({
method: 'post',
url: 'https://notify-api.line.me/api/notify',
headers: {
'Authorization': 'Bearer ' + 'YOUR_ACCESS_TOKEN',
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*'
},
data: querystring.stringify({
message: 'something you would like to push',
})
})
.then( function(res) {
console.log(res.data);
})
.catch( function(err) {
console.error(err);
});
I try it works.
async function test() {
const result = await axios({
method: "post",
url: "https://notify-api.line.me/api/notify",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer [token]",
},
data: 'message=你好哇'
})
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
}
test();
I think you can check response on chrome debugger network.
or provide more information, thx.

How to send client key and secret for authentication in react native

I am making an react native android application in which in need to send client key and client secret to server.
const a = "ck_a332f4d89de6eed37b108f9eda13cfa1e71ce438";
const b = "cs_1c700d679d9613f507479325c1f53be4d3eac858";
const basicToken= base64.encode(a+ ':' +b);
componentDidMount(){
axios.get('http://link.com', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Basic ${basicToken}` ,
//'consumer_key': "ck_a332f4d89de6eed37b108f9eda13cfa1e71ce438",
//'consumer_secret':"cs_1c700d679d9613f507479325c1f53be4d3eac858",
},
}).then((response) => response.json())
.then((responseJson) => {
ToastAndroid.show(JSON.stringify(responseJson),ToastAndroid.LONG)
}).catch((error) => {
console.error(error);
});
}
I have tried using both above code but it gives me 401 error.What i am doing wrong here? How can i send client key and secret to server using axios/fetch api
As you have specified you are receiving an HTTP status code of 401. This implies you are unauthorized. You must log in with a valid user ID and password. Please cross check your token value.