Cannot Basic Auth from React App with Axios or SuperAgent - reactjs

I try to make a GET request with axios and I always get 401. This happens only when I send the request from my react app.
axios.get('http://localhost:8080/vehicles', {
withCredentials: true,
auth: {
username: 'admin',
password: 'admin'
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
Postman GET request with the same credentials and Basic Auth set, works.
If I simply type in my browser the url, a login box appears and with the same credentials, it works, I get what I want.
I tried with SuperAgent too:
Request.get("http://localhost:8080/vehicles")
.withCredentials()
.auth('admin', 'admin')
.then(response => {
return response.body
});
Still nothing.
I saw a question related to this one but no one answered it.
(Basic authentication : failure supergaent+OSX , success on superagent+Redhat , success on Postman+OSX,)
Can anyone point me to the right direction?
Thank you for reading.

Related

How to use axios PUT method in React when there is authentication required?

Like the title says, I need to use PUT method with axios in react, but also I need to have authentication. I am using this api: https://gorest.co.in/ , and on the site as you can see for PUT mehtod, you are required to use access token which can be provided to you when you login onto the site. Now, I have done that, and I got my token, but somehow I still get 401 status code a.k.a I am unauthorized for PUT method, here is what I have done:
const [data, setData] = useState(null);
useEffect(() => {
axios
.put(
"https://gorest.co.in/public/v1/users/6",
{
name: "Test",
body: "This is an updated user",
},
{
headers: {
Authorization:
"my token, for privacy reasons I am deleting it, but it goes here",
},
}
)
.then((response) => {
setData(response.data);
});
});
This is my first time doing PUT method so I am really confused on what I am doing wrong here. If someone could help me, I would appreciate that.
Do you have the word Bearer before your token?
Like:
Authorization: Bearer <auth-token>
How about this?
{
headers: {
Authorization: `Bearer ${myToken}`,
},
}
The website defines the header like this
Authorization: Bearer ACCESS-TOKEN

CSRF Protection with Flask/WTForms and React

Has anyone successfully implemented CSRF protection for a form submitted with React (as a controlled component) to a Flask back-end (ideally with WTForms)? I've seen a lot of partial answers, and one with Django, but couldn't find anything definitive for Flask. My big issue seems to be that I don't know how to send the csrf token to my react front end, store it as a header before submitting my form, then submit my form with the correct token. Any direction would be really helpful.
So, essentially what I did is I set up a route in Flask that can receive both GET and POST requests. React sends a GET request when the component mounts, and Flask responds with the csrf token as a header (done manually). Then React stores this value in state. When the form is submitted, the csrf token from state is sent as a field, similar to the way it is sent in a pure Flask app, where it would be a hidden field. While this technically works, I am curious if this is still vulnerable to CSRF. I think the next best option is to set up CSRF protection on all endpoints, so can try that if this isn't secure.
Flask route:
#app.route('/api/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
print(request.method)
if request.method == 'GET':
return ('', {'csrf_token': form.csrf_token._value()})
elif form.validate_on_submit():
return { 'message': 'Login successful' }, 200
else:
return { 'errors': form.errors }
GET request in componentDidMount:
componentDidMount() {
axios.get('/api/login',{data: null, headers: {'Content-Type': 'application/json'}})
.then(res => {
console.log(res)
this.setState({
csrf: res.headers.csrf_token
});
})
}
POST request when form is submitted:
onSubmitLogin = e => {
e.preventDefault();
const userData = {
username: this.state.username,
password: this.state.password,
csrf_token: this.state.csrf
};
axios({
method: 'post',
url: '/api/login',
data: userData,
headers: {
'content-type': 'application/json'
}
})
.then(res => {
console.log(res);
});
}
Maybe you need flask-security-too lib
https://flask-security-too.readthedocs.io/en/stable/patterns.html#csrf

Why I get undefined when I try to access the value of the session id from the cookies

I'm trying to access the value of the sessionid from my cookies and I get undefined even tho the sessionid is set in the cookies.
My application uses React and for this particular task, I'm using Cookies from js-cookie.
Here is my code
import {urls} from "../../Urls";
import Cookies from "js-cookie";
export async function updateUser (body) {
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
"X-CSRFTOKEN":Cookies.get("csrftoken"),
"sessionId":Cookies.get("sessionid")
}
await fetch (process.env.REACT_APP_BACK_END_DOMAIN + urls.PROFILE,{
method:'PUT',
body: JSON.stringify(body),
headers : headers,
});
}
And here is how the cookie looks like
However, when I console.log both the csrftoken and the sessionId, the csrftoken works as expected while the sessionid is undefined.
Any explanation for this?

"Network Error" with Axios and DjangoREST but request succeeds at the end

So, I am using ReactJS and DjangoRESTframework to build my app.
Now..when I send a request with Postman it works perfectly(ex. 127.0.0.1:8000/api/users/ GET request) and when I try to do it in React with Axios I get a network error but on my local development server console I see that it succeeded.
This is my get request with axios in react:
componentDidMount() {
axios.get('http://127.0.0.1:8000/api/users/', {
headers: {
'Accept': 'application/json'
}
})
.then(res => {
console.log(res.data);
}).catch(err => {
console.log(err);
})
}
And I get an Network Error. But as I said with Postman it works.
One more example is that I send POST request with Axios to http://127.0.0.1:8000/api/users/ and as response I get Network Error as well but on my backend, user IS created.
This is code for my POST request with axios:
let formData = new FormData();
formData.set('email', this.state.emailField);
formData.set('username', this.state.usernameField);
formData.set('password', this.state.passwordField);
axios({
method: 'POST',
data: formData,
url: 'http://127.0.0.1:8000/api/users/',
config: {headers: {'Content-Type': 'multipart/form-data'}}
}).then(request => {
console.log(request.data);
}).catch(err => {
console.log(err);
})
I googled for about an hour to fix this but nothing helps.
Can you be more clear on what you see as Network error? Attach some error messages / Stack trace.
This looks like a Cross-Origin Resource Sharing (CORS)
issue to me. Try configuring CORS on your DjangoRESTframework backend.
This might help you if that is the case.

Using JSONP in react-redux application

I am just trying to get the CORS headers issue caused by missing headers in request out of the way and hence inclined to using JSONP.
Any suggestions/ideas how to use JSONP in a react-redux app? Like how to configure and use it?
In your react component, dispatch an action that is caught by middleware. The middleware should make a call to the jsonp endpoint, probably using jquery's $.ajax method. I also like the fetchJsonp library. Your middleware should then dispatch a new action with the data received by ajax or fetchJsonp, which should be caught by your reducer, and alter the state.
I use fetch in most of cases in react apps:
// payload is your post data
const payload = {data: 'test'};
const options = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
cors: true, // allow cross-origin HTTP request
credentials: 'same-origin' // This is similar to XHR’s withCredentials flag
};
// SEND REQUEST
fetch('http://example.com/', options).then((response) => {
// TODO
}).catch((error) => {
// TODO
});

Resources