Cookies not set on deployed React app on AWS S3 - reactjs

In NestJS i created backend for my app and i used ReactJS for frontend. When i was testing on localhost everything was working fine.
Then i wanted to try and learn some AWS and i made docker image of my backend and deployed it to EC2. After that i got this url:
http://ec2-<SomeNumbers>.<SomeRegion>.compute.amazonaws.com:8080. If i use this url in Postman and do a POST to my login it works fine. I get back JWT as HttpOnly cookie. In my ReactJS app i replaced localhost links with this new link.
I uploaded my ReactJS app to AWS S3 and got this url http://<bucketName>.s3-website.<Region>.amazonaws.com. If i open this it shows correct first page. The problem comes when i fill login form and click login button the JWT cookie is not set so i get Unauthorized.
I really do not know is the problem in my backend, frontend or in AWS settings.
NestJS controller login function:
async login(
#Body() body: LoginUserDto,
#Res({ passthrough: true }) response: Response,
) {
const data = await this.authService.login(body);
response.cookie('jwt', data, { httpOnly: true });
return 'success';
}
ReactJS code:
const api = axios.create({
baseURL: "http://ec2-<SomeNumbers>.<SomeRegion>.compute.amazonaws.com:8080",
headers: {
"Content-Type": "application/json",
},
withCredentials: true,
});
Thanks!

Related

React axios - calling a http endpoint from https webapp

am trying to call a http endpoint from my react web application created using create react app
i am given the below code and a local pem file
caCrt = fs.readFileSync('./ca-crt.pem')
const httpsAgent = new https.Agent({ ca: caCrt , keepAlive: false })
axios.get(url, { params: params, httpsAgent: httpsAgent {color:#0747a6}}) .then( res =>
not sure how i can call it properly from frontend (https web app), i received several "mixed content" error from chrome, understand that i may not be able to use "fs" module from my react app

Client does not receive cookies from server, postman does

There is a server, which serves my client react app at root path. So when I make any request to server from POSTMAN, to login for example, cookies are attached perfect. But when I make request from my client using AXIOS and withCredentials field as well, cookies ain't attached, nevertheless the request is sent good, but no cookies received. I don't think there is any reason to search issues in server code, because postman works with it perfect. In case, there is no CORS errors: server provides client app. I get nice response from the server, with no cookies. Postman gets them.
axios request in react app:
export const login = createAsyncThunk(
'auth/login',
async (credentials: ILogin) => {
// todo: making a request to server
const response = await axios({
url: '/api' + '/auth' + '/login',
method: 'POST',
data: credentials,
withCredentials: true,
headers: {
'Content-Type': 'application/json'
},
});
console.log(response)
}
)
Client doesn't receive cookies, neither on localhost nor deployed app.
As you see, only place where cookies are shown it's network section in devtools, but everything else, including server acts like my second request hadn't any cookie, because in this case, server would answer like: agh, already logged in
P.S: i'm using http

cookies not saving when using express-session

I am using express-session to save cookies into my browser so I can use it for authentication. I am sending a post request from my frontend (React) using axios to the backend and use User.register to save the new user to the database(mongodb)
I am able to save the user to my database however, there are no cookies being saved in my browser.
Frontend post request using axios:
backend post request handler
In your server add this code
app.use(cors({ credentials: true, origin: "http://localhost:3000" }));
Client axios config
const Axios= axios.create({
baseURL: "http://localhost:3001/",
withCredentials: true,
});

Django / React - Production API URL routing issues

I have a backend Django REST API that also helps serve my React frontend. I currently have an issue with my API requests url paths to my Django API in production for every page except my home page...
API URL's that work:
I'm able to visit my home page, within my home page, I have a GET request to my API which works great and loads data as expected. This is the only working GET request of my website because the API URL path is correct to my urlpatterns syntax.
API URL's that DON'T work:
The issues arise when I visit a page OTHER than the home page of my React app. My API requests to Django on other pages are using the wrong URL path according to my network panel (they are also responding with index.html), which has me believe I set up my django URLs wrong.
Please checkout my configuration below:
main urls.py:
def render_react(request):
return render(request, "index.html") #<---- index.html from React
urlpatterns = [
path('auth/', include('drf_social_oauth2.urls', namespace='drf')),
path('admin/', admin.site.urls),
path('api/', include('bucket_api.urls', namespace='bucket_api')),
path('api/user/', include('users.urls', namespace='users')),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
urlpatterns += [
re_path('',render_react) #<---- Serving React index.html
]
Here is an example of the issue:
When I visit this subpage URL:
https://mywebsite.com/try-demo/ra4r7n7mdb
A GET request should be firing off too this URL:
https://mywebsite.com/api/demo/ra4r7n7mdb
However instead of sending the request to the correct URL above, it's sending to this url:
https://mywebsite.com/try-demo/api/demo/ra4r7n7mdb
This is the same problem for other parts of my website that are requesting data from my django api. So when I visit my login page (https://mywebsite.com/login), and enter my details to request an authentication token. The request for the token should be:
https://mywebsite.com/auth/token/
but instead its requesting the data through this:
https://mywebsite.com/login/auth/token/
How to fix this?
my url patterns has a catch all request, my react is then able to 404 pages that don't exist. The only problem I have is how my React app is requesting data to my API in production. (again the API request on my homepage works fine) Why are my other requests appending the first URL path of my React router URL's?
I don't want to clog this post with code, so please let me know what other information I should present here to help solve this problem?
UPDATE
I have solved the API request issues to my server. The paths are now correct according to the network panel. However, the issue still remains where I seem to be only getting my index.html as the response for these API requests (they should be data responses, not index.html)
Here is my catch all regex for Django
re_path(".*/", render_react),
re_path(r"^$", render_react)
NEW EDIT
I am now able to get one of my API data requests to respond with JSON data (as should be expected)
Here is the URL of the API request that works:
https://mywebiste.com/api/demo/idoyem1l4k/
These still don't work:
https://mywebsite.com/api/demo/tabledata/idoyem1l4k
https://mywebsite.com/api/demo/graphdata/idoyem1l4k
How I make requests:
import axios from 'axios';
const baseURL = `https://mywebsite.com/api`;
const axiosInstance = axios.create({
baseURL: baseURL,
timeout: 9000,
headers: {
Authorization: 'Bearer ' + localStorage.getItem('access_token'),
'Content-Type': 'application/json',
accept: 'application/json',
},
});
export const getData = async (dispatch, slug, cancelToken) =>
{
try
{
console.log('fired demo request')
const response = await axiosInstance.get("demo/graphdata/" + slug, { cancelToken });
dispatch({ type: 'FETCH_SUCCESS', payload: response.data });
} catch (err)
{
if ('isCancel' in err && err.isCancel())
{
return;
}
dispatch({ type: 'FETCH_ERROR' });
}
}
How can I return the actual data requested instead of my index?
It makes sense, that it always returns the index.html. Your catch all regex prevents your API calls to be called, so it always resolves to render_react. I think you have 3 options.
You try to put the catch-all patterns to the bottom of all urlpatterns - I'm not sure how reliable this is though
You do not catch all by deleting re_path(".*/", render_react), and explicitly name every react page you want to use
You change the catch-all regex to exclude your Django apps with something like re_path("(?!api).*/", render_react),
I would choose option 2, as it gives you most control of your urls

Cookie handling in react and expressjs

I'm trying to send cookie from the server to the react app and use this cookie as auth in the middleware. With the postman, everything is working, but in the browser, it is not.
As I have read some tutorials I need to set up cors and here is the snippet of my server-side app.
app.use(cors({ origin: "http://localhost:3000/", credentials: true }));
res.status(200).cookie("login_auth", token, { httpOnly: true, domain: "http://localhost:3000" }).json({ user });
Then I'm sending the post request
axios.post("http://localhost:5000/user/login", { email, password }, { withCredentials: true })
but when I check the cookie storage for my app there is no cookie and further, I have no idea how to send the cookie back to the server to fulfill the middleware. In postman it is all done so easily.
I can save the cookie with the "js-cookie", but I don't think it is the right way to do it.
Cookies.set("login_auth", response.data.token);
Somebody help?

Resources