Share cookies received from external source between Client and Server in NextJS - cookies

I got a backend, NestJS GraphQL, and I got authentiaction on it's side. On signIn query it returns 3 Set-Cookie headers: is_authenticated, access_token and refresh_token. I use useLazyQuery hook from apollo to make a signIn request. Everything works until I want to use these cookies server-side e.g. getServerSideProps. How to sync client and server cookies in NextJS? Do I have to set them manually?
When I console.log getCookies(ctx), ctx.req.cookies it returns empty object. On client-side getCookies() also returns empty object, but these cookies are set, because I also have a cart-id which sets the cart user can use, and it works properly, after refresh, restart browser and even restart my PC. Where is the problem then?

Related

Null Session in the django-restful framework

Django rest framework
I'm setting the session key once a user logins in
request.session['id'] = 1
Then when I try to access it in the class view like
id = request.session.get('id', 0)
It is null [0] if the end-point call is made from the browser but it returns 1 if end-point call is from postman...
I need your guidance...
Session cookies are browser-specific - they are only sent back to the server if the request comes from the same browser that received the cookie in the first place.
Postman is not a browser - it is simply making raw HTTP requests. It will not send any cookies back, so of course you will not see session data.
This behavior is entirely expected and by design. Sessions are only persisted per-browser.
If you want to make API calls and authenticate them, you should use token authentication instead, which can be passed in the Authorization header of requests and is not tied to a browser session.

Send Ajax request with cookie from 3rd Party Iframe - Safari 14+

I have a server side application that uses cookies for session management. The browser has some script that sends an ajax request to add information to the session. This is working well and in production.
The business wants to be able to insert this application in other companies' websites via iframes. ie myapp.com is in an iframe in otherbusiness.com and when the user clicks a button in the application in the iframe launched from myapp.com, it sends a request with a cookie that contains the session id to update the user's session on the myapp.com server.
For the browser to be able to send a cookie, 3rd party cookies needs to be enabled by setting the cookie options of SameSite=None and Secure. This works for all browsers except Safari.
Safari no longer accepts 3rd party cookies.
The only solution I can come up with is to use session ids in the URL but this is a little cumbersome.
Can anyone suggest a better option or perhaps a good implementation of session ids in the url?
I used hidden html fields to pass the session id and expiration.
My server side code checks for a cookie if it cannot find it, looks for the session id and expiration in the hidden fields.
This avoids security issues with passing the id in the url. It is a little clumsy to implement but it works.

Using JWT authentication with Django/DRF and Storing JWTs in HttpOnly Cookies

I am trying to build a web app using Django and DRF at the back-end and ReactJs at the front end and I want to keep them separate (i.e. avoid Server Side Rendering).For authentication purposes, I want to employ JWT and I am using djangorestframework-jwt for that. I have read it at several places that it is not secure to store JWTs in the local storage so I am trying to use HttpOnly cookies for that. One can achieve that by configuring the django server to send HttpOnly by overriding the following default settings of the drf-jwt package in the settings.py file of your project JWT_AUTH = { 'JWT_AUTH_COOKIE': '<cookie name>', } which is set to none by default. The server sends the httpOnly cookie as anticipated but there are a few issues I am facing:
1.Same Domain Restraint
I am aware that httpOnly cookies wont be attached to the request headers unless the request is being made to the server which is hosted on the some domain. In my case I am using localhost:8000 for django and localhost:3000 for my react project so the browser doesnt attach the cookie as the request is made to a different port. I tried running both app on port 3000 simultaneously, and the browser did attach the cookie in the header and I did get the a 302 response from the server. However, it opened door to all sorts of problems due domain clash. I reckon I can solve this problem using nginx reverse proxy or something like that but I am not sure about it. Do guide me how can I serve both apps on the same host during the development.
2. Token Refresh Problem
When I refer to the view setup to refresh the token, I run into a bad request error even when the browser does attach the cookie along the request header. This is the server response in the browser
{"token":["This field is required."]}
Thanks if for reading it all the way down here!
In order for things to be secure:
You need CORS (Quickstart: CORS_ALLOWED_HOSTS=["http://localhost:3000"], CORS_ALLOW_CREDENTIALS=True)
The short-lived token (session) cookie (5-15mins), should NOT have HTTP-ONLY setting
The refresh token cookie SHALL have HTTP-ONLY setting
Then your basic flow is:
On login Django creates session token and sends it
Your SPA reads the cookie and adds its value to the authorization header (Authorization: JWT ...token...)
Any request to Django should be made with that Authorization header
The refresh flow is:
Send a request to the refresh token endpoint following the documentation of the library you use
Django then reads the HTTP-ONLY cookie and verifies it
If valid, Django sends a new refresh token as HTTP-ONLY cookie along with a new short-lived token session cookie
Once the refresh token has expired, you log the user out.
An article here goes into detail using GraphQL, but the cookie part and handling of most of the frontend code you should be able to adapt to REST.

Session with Django

In a Home page, i have a form login. in the view.index of the app "Home", after authenticate, i create the ssesion. And after, i call the app "Places" if the authenticate is okey,
request.session['user'] = username
request.session.set_expiry(900)
return HttpResponseRedirect('/places/')
in the settings of the project i configure the SESSION_SAVE_EVERY_REQUEST = True.
How can i send the session to all others pages of the project, and log out the user when the session is expired ?
HTTP is a request response protocol.
This means that the server has no way to to communicate to the client without the client initiating the conversation. So the only way to do something like this is native Django, is to have the client periodically check to see if the session is still ok.
One way to achieve this is with a background ajax call (perhaps using setInterval in javascript) which checks the session, and if it's not any good anymore (either by expiration or the user has been disabled etc) then redirect them back to the login page.
Another approaches could involve sending the expiry time to the client so that it only checks the session when it would have expired (though this wouldn't pick up on users being disabled) or having a websocket server which pushes this information to the client.

Remove Cookies in Worklight Adapter : multiple sessions using same adapter based authentication

I am using Worklight Adapters and using Authentication based adapter, which verify credential via a third party webservice (grails server).
When testing with one user, every thing is fine, but once I start using multiple users accounts, I found that all users connect to the same session, with the same Cookie JSESSIONID
I think worklight adapter is adding cookies from previous requests, and that's equivalent to a browser connecting to différent accounts, without removing old cookies / logging out.
When debugging, I can see that I have in the authentication request response headers, when the first user login:
"Set-Cookie":"JSESSIONID=63850CB333E7C279DC6D5B1D973B21E7; Path=/"
and when the second user login, there is no longer "Set-Cookie" header in the response.
Anyone have a solution, or workarounds ?
How can I force worklight to remove existing cookies when connecting to the authentication webserver ?
In your adapter procedure you should add the attribute connectAs="endUser". This way each user will create a unique connection to the authentication backend and they will not share the same session ID.
I force a logout on window close. Something like this:
function wlCommonInit() {
window.onbeforeunload = function() {
WL.Logger.debug("logging out");
WL.Client.logout();
};
}