How can i remove session cookies from passport js authentication? - javascript

I have a project right now, but i cannot figure out how i can remove session and req.user from the client side.
I know that in node js/express js you do req.logout() and req.session = null, but that only removes it in the backend side. I am currently using react and it does not work when i call the api for removing the session.
Any idea?
the session cookies is session.sig and session

when client(typically browser)visit a web server(like nodejs based server you used), a session was built between client and server. As far as i know, session stores on the server side, normally it will send back the session's id(named sessionId or jsessionid ...), then web connection was built.
So if you would like to remove a session on the client side, you just need to remove the sessionId attribute's value in the cookie with this
document.cookie = "sessionIdKey=;"
you should replace 'sessionIdKey' with the key in your chrome dev tools => application => cookies => sitecookie place
this will end session connection, when this session time out, server will delete the session finally.
update: if you'd like to delete all cookies(sessionid between them), reference this: Clearing all cookies with JavaScript

Related

Cookies dont get stored because of path with req.cookie

Hello I got a similar problem as this one : Cookies don't get stored in localhost but the difference is that for me it works when I put path:'/' (the default path) and path:'/login' (which is the current client side page when the cookie is trying to be stored at the end of the login process) but it doesn't for any other path.
res.cookie(`api`,token,{
domain:'localhost',
path:'/account',
expires: new Date(Date.now()+7*24*60*60*1000),
httpOnly: true
});
My server is on port 3000
Edit: I need to add that I have a middleware like this in my app.js file
app.use("/auth/", authRoutes);
authRoutes is the module file where I put the different routes like /login and /register. So when I submit the login form it is calling the /auth/login route server side which will execute the login function where I try to create the cookie after all the email/password verifications. I just tried path as '/auth' in the res.cookie function and it actually worked. Could that be the problem ? That I am trying to create a cookie in a function that is considering '/' as /auth/ because it is a middleware. I don't know if it's clear but I was thinking maybe it is somehow related even if I wouldn't understand why.
Edit 2 : In my app, Express serves static files of my react front end app. What I want to do is put a httponly cookie on the user's browser after login that will be sent back to server only when user visit the '/account' page to verify the user's identity and if he is still connected.

Sending cookies between Flask and javascript and using Flask-session

I am a web-dev noob but I'll try my best to be clear about the problem, explain my approach, and what I've tried. I also include imports in-case those are causing the problem but I'm pretty sure I've isolated it to what I describe.
I am trying to use Flask-session to keep information private but some values are "lost". This code is trimmed down significantly for simplicity. The user lands on /send and we render the loading template. loading.js does fetch() on /deploy while it runs an animation, then() we go to /results when the deploy function is done.
loading.js
function navigate() {
window.location.href = 'results'; // redirect to results page when done!
}
// deploy the contract while the loading screen goes then navigate to results page
const data = fetch('deploy').then(navigate);
loopThroughMessages(messages);
main.py
from flask_session import Session
app = Flask(__name__,
static_folder='static',
template_folder='templates')
# for the session, i.e passing values
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config.from_object(__name__)
Session(app)
#app.route('/send')
def main():
# take url parameters and do stuff with them
return render_template('loading.html')
#app.route("/deploy")
def deploy_contract():
session['contract_address'] = some_fnc()
# fetch() requires that this function return a json
return {}
#app.route("/results")
def serve_results_page():
# pull saved values from the session
data = {'contract_key' : session['contract_address']
} # calling session here causes the error, the contract_address key doesn't exist
return render_template('results.html', data=data)
So contract_address is saved to the session but when we get to /results, the server has no way to associate that session with the client.
We want to keep our contract_address private so sending it to loading.js is not an option. I'm guessing that since http is stateless, I need to pass a cookie to and from my js and python files but I'm a bit lost on how to implement it. Are cookies unnecessary (because the server doesn't actually need to receive any data from my js files)? Should I be using redirects or something besides fetch()?
Hacky fixes, different approaches, and resources are all welcome. I feel like I'm close, like there's a simple way to use cookies that I'm overlooking.
I will be continuing to research and detail the approaches I'm considering
Edit1: Looking at Flask's should_set_cookie method
Try fetch with credentials:'include' to cause browsers to send a request with credentials included on the server side calls:
fetch('deploy', {
method: 'GET',
credentials: 'include'
}).then(navigate);
Using this, you will access session['contract_address'] in the results route.
The flask-session sets a cookie with a key session in your browser, fetch with credentials:'include' includes this cookie value in the network call.
Session in flask is implemented as a client session, saving all session content as client cookies. The flask-session extension provides some other server storage for session. E.g. app.config["SESSION_TYPE"] = "filesystem" save session content in a file on the server.
But both of the approaches still depends on Cookie. The server-side session storage need to get a session_id from client Cookie.
You need to enable cookie sending on Fetch API.
fetch, sending cookies

How to check Node session cookie expiration from browser

We're using Node + Connect to manage sessions for our app, which is a single-page application (SPA) built with Backbone.js. I'm trying to write some code which will check from the client if the session is still valid. I know I can do it in Node itself, but as this is an SPA, I need to be able to do it completely client-side.
My first thought was to read the connect.sid cookie with jQuery and if it wasn't there, then that would mean that the session is expired. Unfortunately, that session cookie is protected with the HttpOnly flag and for good reason. I don't want to disable that.
My second thought was to write a second, parallel cookie every time the connect.sid cookie is written. This second cookie would only store the expire date of the session cookie and would set HttpOnly to false so that the client could read it.
So my question is, how do I go about writing that second cookie, or is there a better solution for being able to detect session expiration status from the browser?
I know how to write cookies with Node, but I'm not sure where to put the code so that it will fire every time that Connect writes the main connect.sid session cookie. Additionally, I would like to be to read the expire date of the session cookie so that I can write it in my parallel cookie.
UPDATE: To be clear, I'm not looking to read the expiration date of the session. I know that JS cannot access the expires date of a cookie. I just want to see whether or not the cookie exists, as it will only exist when it's valid and therefore its absence is enough data for me.
updated after clarifications in comments
Add another middleware right next to your session middleware. Excerpt below assumes express, but if you are using connect without express you should be able to interpret accordingly.
app.use(connect.session(sessionOptions));
app.use(function (req, res, next) {
res.cookie("sessionIsAlive", "1", {
//just make sure this matches your expiration time of the real session cookie
expires: new Date(Date.now() + 900000),
httpOnly: false
});
next();
});
Then you can check for the existence of that via javascript in the browser. And just FYI connect writes a new cookie with an updated expiration time on every response. That's how the "expires after N minutes of inactivity" behavior is implemented.

Getting the session details via websockets in Node.js

I've created a project in Node.js, users are able to create a 'room'. Users login via a html form which submits their details as a HTTP request. The server then adds a token to their session 'req.session.auth = true'. I want to broadcast socket messages to users where their .auth token is true.
Question:
how can I access session information outside of a HTTP request? whilst using (if correct):
var MemoryStore = require('connect').session.MemoryStore,
sessionStore = new MemoryStore();
e.g.
socket.on('message', function(data){
//Access user session here.
});
There are a lot of things to be said here, but they are all explained better in the following post:
http://www.danielbaulig.de/socket-ioexpress/

How do sessions work in Express.js with Node.js?

Using Express.js, sessions are dead simple. I'm curious how they actually work though.
Does it store some cookie on the client? If so, where can I find that cookie? If required, how do I decode it?
I basically want to be able to see if a user is logged in, even when the user is not actually on the site at the time (like how facebook knows you're logged in when you're on other sites). But I suppose to understand that I should first understand how sessions work.
Overview
Express.js uses a cookie to store a session id (with an encryption signature) in the user's browser and then, on subsequent requests, uses the value of that cookie to retrieve session information stored on the server. This server side storage can be a memory store (default) or any other store which implements the required methods (like connect-redis).
Details
Express.js/Connect creates a 24-character Base64 string using utils.uid(24) and stores it in req.sessionID. This string is then used as the value in a cookie.
Client Side
Signed cookies are always used for sessions, so the cookie value will have the following format.
[sid].[signature]
Where [sid] is the sessionID and [signature] is generated by signing [sid] using the secret key provided when initializing the session middleware.
The signing step is done to prevent tampering. It should be computationally infeasable to modify [sid] and then recreate [signature] without knowledge of the secret key used. The session cookie is still vulnerable to theft and reuse, if no modification of [sid] is required.
The name for this cookie is
connect.sid
Server Side
If a handler occurs after the cookieParser and session middleware it will have access to the variable req.cookies. This contains a JSON object whose keys are the cookie keys and values are the cookie values. This will contain a key named connect.sid and its value will be the signed session identifier.
Here's an example of how to set up a route that will check for the existence of the session cookie on every request and print its value to the console.
app.get("/*", function(req, res, next) {
if(typeof req.cookies['connect.sid'] !== 'undefined') {
console.log(req.cookies['connect.sid']);
}
next(); // Call the next middleware
});
You'll also need to make sure the router (app.use(app.router)) is included after cookieParser and session in your configure section.
The following is an example of the data stored internally by Express.js/Connect.
{
"lastAccess": 1343846924959,
"cookie": {
"originalMaxAge": 172800000,
"expires": "2012-08-03T18:48:45.144Z",
"httpOnly": true,
"path": "/"
},
"user": {
"name":"waylon",
"status":"pro"
}
}
The user field is custom. Everything else is part of session management.
The example is from Express 2.5.
I have never used Express.js, although according to their documentation on the subject it sounds like:
Cookies are stored on the client, with a key (which the server will use to retrieve the session data) and a hash (which the server will use to make sure the cookie data hasn't been tampered with, so if you try and change a value the cookie will be invalid)
The session data, as opposed to some frameworks (e.g. Play Framework!) is held on the server, so the cookie is more like a placeholder for the session than a holder of actual session data.
From here, it looks like this session data on the server is by default held in memory, although that could be altered to whatever storage form implements the appropriate API.
So if you want to check things without a specific req request object, like you said, you need to just access that same storage. On the bottom of the first documentation page, it details required methods the storage needs to implement, so if you're familiar with your storage API, maybe you could execute a .getAll() if something like that exists, and loop through the session data and read whatever values you want.
I'm curious how they actually work though.
Try to look at this answer and wiki stuff.
Does it store some cookie on the client?
Yes, it's usually a cookie with assigned session ID, which should be signed with a secret in order to prevent forgery.
If so, where can I find that cookie? If required, how do I decode it?
You shouldn't mess with a session cookie on the client side. If you want to work with sessions on the server side you should check out related express.js and connect docs.
In addition to already excellent answers, here are 2 diagrams I've created to explain Express sessions, their link with cookies and store :
chocolate cookie:
strawberry cookie:
Diagram's explanation:
Each cookie has a unique "flavor" (or sessionId). When the strawberry cookie is presented to the server (within the HTTP request), the server recognises this flavor and loads from the store the corresponding datas: Rosie's datas, and populates req.session with.

Categories

Resources