Press "Enter" to skip to content

Session Authentication in Express


hey guys welcome back the cold roll my
name is Alex so in the last video we
talked about authentication and very
general terms in this video when I get
specific and I want to show you how you
can implement session based off and
nodejs so what I’m gonna do is I’m gonna
head over to my terminal over here I’m
gonna make a new directory we’re gonna
call it session auth like this
let’s CD into it so we’re gonna
initialize a new project I’m gonna run
NPM in it – why and we’re gonna create a
new file let’s call it at Jes this will
be the main file for the server and
let’s open this in Visual Studio code
what I’m gonna do for this tutorial is
I’m going to use a library that’s known
as Express session so let’s look for it
this one is a library that acts as a
session middleware for Express so let’s
go ahead and install it I’m gonna copy
the name and I head back to the terminal
we’re gonna be using Express as well so
what I’m gonna do is I’m gonna install
Express as well as Express session both
of those once that’s done I’m gonna also
npm install a dev dependency of node mon
as well as standard no standard is not
mandatory for this tutorial but i like
to use it as a linting style guide so
I’m gonna use it myself so let’s install
those two dependencies so I’ll head over
back to Visual Studio code so what I’m
gonna do is I’m gonna create a constant
for Express we’re gonna require Express
library we’re also going to require
session from Express session of course
so what we need to do is we need to
create an app constant which will be the
Express application and we need to call
Express and once that’s done we can do
app listen so the first argument will be
the actual port so it can go ahead and
create a variable for it in fact what
I’m going to do is I’m going to extract
it out of process and just so that we
don’t have to pass it ourselves I’m
going to provide a default in this case
this could be 3,000 so once that’s done
we need to pass a callback this is just
basic Express stuff
in fact I don’t even have a function
body I’m just gonna do a console log
we’re gonna do HTTP to forward slashes
localhost and we’ll put in the port
and this should be it so let me double
check all the dependencies have been
installed so I’m gonna head over to
package.json what I’ll do next is I’ll
create a helper dev script so in there
I’m gonna call node Mon on the app.js
file so this will start the development
server and also listen to any changes to
the file system and restart the server
as well so once that’s done let’s do a
quick test back in the terminal I’m
gonna clear it out let’s do NPM rondelle
so the server starts at port 3000 of
course there’s nothing there yet all
right so once we require Express session
what we can do is we can basically call
it as a middleware let me actually look
for an example this is what we can do we
can call app dot use just as any other
middleware and Express and we can call
that session as a function passing in a
config object I’m gonna do app use we’re
gonna call session as a function passing
in a config object right so as far as
the options we can start with the cookie
object so if I go back in here I’ll put
in cookie this will be the configuration
for the actual session cookie so we can
go ahead and pass the domain attribute
for example this will be used to
configure the domain attribute on the
cookie but if they don’t specify the
domain most browsers will by default
consider the cookie to apply only to the
current domain so we could actually go
ahead and skip that part
the next attribute or flag we could also
specify is the expires attribute in this
case we could set it to a date object
but they do actually recommend to use a
different attribute which is maximum age
so we’re gonna use that one instead
so get skip the expires attribute for
now the HTTP only flag will allow us to
make the cookies server-side only so
this means that each ava’s script on the
client side won’t be able to access it
luckily for us this attribute is already
set to true by default so we’ll get
continue using the defaults and we can
just skip this attribute for now now the
maximum age is the interesting part so
this one we actually have to configure
so this one specifies the number of
milliseconds until the time when the
cookie is going to expire so what I
shall go ahead and provide a time period
after which the cookie will no longer be
acceptable to the server in fact if we
don’t specify any maximum age or any
expires attribute
browsers will treat the cookies such
that it’s going to be a session cookie
now I mention it before basically what
that means is that the cookie will
expire as soon as the browser is closed
by the user so in this case we can
actually go ahead and specify the
maximum age let’s go ahead and do
exactly that now the maximum age will
differ depending on the application so
this could be something like one hour or
this could be something like two hours a
day or even a week so what I’m going to
do in this case is I’m gonna try to get
the maximum age out of the configuration
or environment variables so we can call
it as session lifetime and in this case
we could default to two hours for
example so what I’ll do next is I’ll
actually create a constant for it so
it’s due two hours so once again as I
said before this will be in milliseconds
so we can provide 1,000 so this will be
one second we can multiply it by 60 so
this is going to be 60 seconds or one
minute we multiply by 60 once again this
will be 60 minutes or one hour and I
will be multiplied by two this is gonna
be two hours and this is exactly the
intent of this variable so once we have
a default we can actually go ahead and
use the variable now the utility of
providing defaults to these variables
from process and is such that you don’t
have to pass them yourself from the
command-line so if you start the
application without any custom variables
provided to it the application will
still start so we can actually go ahead
and try to use some reasonable and
sensible defaults without requiring any
explicit variables to be passed manually
so that’s good so far we have a maximum
age the next thing we could also specify
would be the path now in this case by
default its forward slash meaning
everything on the current domain which I
think makes sense for most sites so we
can actually skip that part we can use
the default forward slash the next thing
we could use is the same site attribute
for example we can pass strict elack’s
we could also provide true which is also
going to default to strict or it could
set it to false in essence what it means
is like I said before in the previous
video if you said that attribute that
means that in theory the browser will
only accept a cookie if it’s coming from
the same origin or in other words from
the same domain and this also of course
has an implication for CSRF so let’s go
ahead and set that attribute as well
when I put in same site if we could set
it to true we could of course also set
it to
strict this is gonna have the same
implication or effect in this case next
up we have the secured a tribute this
one is simple the true value is
recommended by default it’s false so
what I’m going to do is I’m actually
going to set it conditionally so if we
are in production environment and then
that attribute has to be true but if we
are developing it’s fine to keep it as
false so let me go ahead and create that
constant in fact this one is going to be
based on node environments so let me go
ahead and grab that as well so node
environments we’re gonna default to
development if it’s not provided and so
if that node environment is in fact
production then in prod will equal to
true and then secure is going to be true
as well
so this only makes sense to set if you
have an HTTP channel enabled next up we
also have the name attribute so this one
could be a custom name for your session
ID cookie this one is actually outside
of the configuration for the cookie so
we can go ahead and for example use a
variable so let’s go ahead and create a
session name environment variable we can
default to s ID or session ID so let’s
go ahead and use that as the name so
let’s save the file back in here
proxy we can skip we save is the next
option we have to consider this one
controls whether these session needs to
be saved back to the session store even
if it wasn’t modified during the request
so for authentication and makes sense to
set that option to false because that
the session was never modified during
the request it really makes no sense to
write to the store and waste your
connection resources because oftentimes
that store will be a Redis store or a
database it’s really not that wise to
create an actual connection every time a
request is issued especially if this
session never changed so we’re gonna go
ahead and set that option to false
because by default it’s true and as they
say the default option has actually been
deprecated might change in the future
but right now it’s true so we’re gonna
set it to false explicitly now a rolling
is another option this one controls
whether the server will set a cookie for
every response in our case it only makes
sense to issue the cookie if you are in
fact a
to the system so if you’re not
authenticated there’s really no
identifier to issue back to the client
so the default value is false and it
makes sense for us so we can go ahead
and skip that now save on initialize is
another option we can control those it
turns out the library will create a
session for every connection or every
request but it makes no sense to save
that session to the store if this
session was uninitialized so what they
mean by uninitialized is that the
session was created as empty but it was
never modified during the request so
once again the session will still be
created for every request but it makes
no sense to actually save it to the
store so it’s still going to remain in
memory for that particular request or
connection to the server so for
authentication and makes no sense to
store empty sessions and because the
default value is true we need to go
ahead and set it explicitly to false so
let me go ahead and call save and
initialize we’re gonna set it to false
and then another required option we need
to pass is a secret so the secret will
be the actual symmetric key that’s going
to be used to sign the cookie once again
this is used to protect the cookie
against the tampering because the
signature will be based on the contents
of the cookie so if the contents of the
cookie are modified they will no longer
match the signature of that cookie so we
can go ahead and provide a secret so let
me go ahead and set a secret
once again I’ll create a variable for it
we can call it session secret like this
let me grab that variable we’re gonna
pass it in here and as a default what
can provide a random string or any
sentence so this will do for a tutorial
but of course it needs to be a sensible
value for an actual application but
we’ll save it for now the next option we
could also provide will be this store so
as it turns out this library has
multiple implementations for different
databases and session stores so for
example there’s one for Redis that we
could use there’s one for Mongo there’s
one for memcache and even firebase in
this case if we don’t provide it it’s
actually going to default to the
in-memory store so we can go ahead and
use that one for now on set we can skip
that option otherwise we can also access
the session on the request object for
every connection to the server and we
have a bunch of methods on the session
like regenerate or destroy for example
this one will be useful when the user
actually logs out and if
other ones as well so this is good for
now so once again to recap we’re
providing a few custom options to the
session middleware in this case we’re
setting a custom name this will be a
session ID where s ID we’re also telling
it not to store the sessions back to the
story if they were never modified during
the request we also don’t want to save
any uninitialized or new sessions that
have no data inside of them it makes no
sense to store them for authentication
we also have a custom secret in this
case a dummy string that we don’t want
to expose to the client this will be a
secret used to sign the cookie
I’ve also have a few options for the
cookie itself so once again by default
it’s going to be HTTP only we also
provide a maximum age in this case with
default to two hours we set same site to
true and we also have the security Butte
this one is set to true only if the
application is in production mode so for
development it’s going to be false so
that’s it for the session configuration
now we can actually move on into the
authentication parts so what we can do
is we can create a few routes here so
for example we’ll have the login route
this is where the user will be able to
log into the app so we’re gonna show a
form with a few inputs to login we’re
also going to create a route to register
now both of those will also have
corresponding post routes so the first
post will be for the login this is where
we’re gonna post our email and password
in the second one will be where we post
an email and password to create a new
user and we can also create another
route so this one will be the Welcome
page so this will be slash this will be
the main page or you could say the
landing page for the website and we’ll
also have slash home you could also call
it / – board for example this is where
the user is going to be redirected upon
login but I’m gonna go ahead and keep it
as home for now and finally we’re also
going to add a post route for a logout
so this is where the user is going to
post to log out of the application of
course all of these are going to have a
similar or actually the exact same
signature so let me go ahead and target
all of them we’re gonna have requests as
well as a response object so for the
main route we can go ahead and do
ra’s Datsun we can go ahead and send
some HTML now of course in the actual
application you would send the proper
HTML structure with the HTML at the root
you’ll have your head section your body
section and whatnot in this case I’m
just going to send a simple h1 let’s say
welcome luckily for us this will still
be rendered properly by the browser so
we can include also a bunch of links so
we’re gonna have an a tag to login if
they want to login to the app we’ll have
one to register as well so let me copy
that so it’s have a register route now
the user is authenticated we’re actually
going to have a set of different links
so we can have a link to home or the
dashboard and we can also have a form to
log out so we can go ahead and create a
form with a post method the action will
be slash logout and this is gonna go to
the logout route that we created over
here and so what we’re gonna do inside
this form is we’re gonna have a button
and we’re gonna say logout so by default
this button will be type submit’ and
it’s going to trigger the form submit
event and this is get opposed to the
slash logout route and the user will be
logged out of the application now we
want to display a set of links depending
on whether the users authenticated
through the application so what we can
do is actually let’s take a look at
request dot session object
it looks like the application is running
fine so let’s go ahead and visit it in
the browser so if i refresh as you can
see we get a bunch of links and if i
look back in the terminal you can see
that currently the object only contains
the cookie but it doesn’t contain any
actual data so once we start putting
data on that object it’s going to be
placed at the root of the session object
so what we can do is we can in fact
check whether the session contains a
custom variable so for example we could
put the ID of the user to the session if
they are authenticated like this so in
fact for the login routes once we do all
of the validation and all the
verification of the credentials we can
actually go ahead and do request dot
session user ID and this is where we can
actually set it to the ID of the user
that’s authentic ated I’m gonna comment
this for now what we need to do first
actually is we need to go ahead and
create a store for our users now in this
case I’m going to keep it simple and I’m
going to create a constant I’m gonna
call it users this will be an array of
objects so the first user object let’s
say will have an ID of one could be Alex
email I’m just gonna do Alex at
gmail.com we’ll give it a password again
I’m gonna keep it simple so I’m gonna
pass in plain text let’s call it secret
and I create another object in fact let
me do another one I’ll have three so ID
to three let me make it a max user and
the last one will be haggard because why
not so let’s do Haggard and the password
will be secret so now that we have three
users we can actually go ahead and use
their IDs to be placed in this session
so what we can do is we can check
whether these session contains a user ID
once again if we do a console log of
that user ID as you expect it’s going to
be nothing so let me try to do your
fresh once again if I look at the
terminal as you can see we get undefined
there’s nothing in the session yet
because we don’t have any session save
in memory or in the session store yet so
we can actually go ahead and rely on
that user ID as you’re gonna see it’s
gonna come back into the picture in a
second but for now we’re just gonna
check if we have a user ID in this case
we’re gonna show the link to home as
well as a format a post to logout
otherwise we’re gonna show a bunch of
links to the login page as well as the
registration page so let me go ahead and
paste those so I’m gonna delete this and
now if I go back to the browser i
refresh and as you can see we get the
login and the register page and once
again if we get a valid user ID so for
example I’m gonna set the user ID to one
I’m gonna save refresh and we see the
link to home as well as logout button so
next we can work on the home page and
this one will be simple I’m gonna do
where as ascend will have an h1 let’s
say home will have a link for example
this can link back to the main page like
this and we can also have a list and
here we can put a name of the user and
we can also display the email
of the user that’s logged into the
system so we’re gonna go ahead and
inject them in a second for now let’s
just save it like that so now for the
login page this is where we’re gonna do
a res dot send once again I’m just going
to send an h1 let’s do a login we’re
gonna have a form so this form will have
a method the post the action will be
slash login once again it’s gonna go
through this slash login post route that
we’ve created so what I need to do next
is we need to have an input so let’s
have an input of type email this will be
the users email the name we can set it
to email we can have a placeholder email
and required as well let’s have another
attribute for password so I’ll go ahead
and put in password and finally we’ll
have an input with type submit’ so this
will be to submit the form so this
should be good for now now for the
register page I’m gonna do the same
exact thing except I’m gonna put in
register and I just noticed a typo this
of course needs to be required with ad
at the end like this this is the built
in html5 I believe attribute this will
make the inputs required right then the
next thing I’ll do is also put another
input in this case this will be type
text so it’s gonna be the default type I
can skip it and I’m also gonna have a
name this will be the actual name of the
user and we’ll make it required as well
and of course this is gonna go to slash
register so this should be good so far
so let me go back let me try to go to
login as you can see we get the login
page and could also be useful to put a
few links at the bottom so for the login
page I’ll have an H ref to register so
if they don’t have an account they can
go ahead and create one and I’m gonna
have the same link in this case it’s
gonna go to login so if they already
have an account they can go ahead and
login to the app let me see how this
works we have a register link and login
so it looks good so far there’s no
styling it’s a simple server-side render
but it’s perfect for a very simple down
so now we can actually go ahead and wire
it up to the post methods over here now
we’re gonna need to work with the body
of the request and that’s why I’m gonna
go ahead and install body parser so let
me do npm install of body parser like
this once it’s installed what we can do
is we can go ahead and call app dot use
as the middleware so that’s actually
import body parsers so it’s two const
body parser require body parser like
this so we’re gonna pass body parser URL
encoded and I’m going to pass an option
of extended set to true this is the
default option but we still have to pass
it explicitly otherwise we’re gonna get
a warning so once we do that we should
be able to access the request body it’s
going to create a few middleware options
because if you go to the login page it
only makes sense to log in if you’re not
logged in already it only makes sense to
register if you are not logged in
already so if you’re in fact
authenticated it makes sense to redirect
the user back to the home page and on
the same notes users should not be able
to go to the home page themselves as you
can see I can go to the home page even
though I’m not authenticated so we need
to go ahead and put some kind of a
protection there so what we can do is we
can create a couple of minutes so we can
create one constant we can call it
redirect login so this is gonna accept a
request response and next we need to
have access to the next attribute so we
can call it so again we’re gonna rely on
the user ID from request session so if
we don’t have a request session user ID
that means that the session object is
still uninitialized so that means we
didn’t put any data to that session and
that session is not stored to our
session store so in fact the user is not
authenticated so what we can do is we
can do res dot redirect and we’re gonna
redirect them to slash login and if we
already have a user ID we’re just gonna
call and X like this so now this
function what we can do is we can apply
to the slash home route so what this is
gonna do is it’s gonna check if the user
is authenticated and if they’re not
authenticated they’re gonna be
redirected to slash login so it’s gonna
have a protection layer behind the home
route so before we send the HTML and
before we
actually show the dashboard to the user
we’re gonna first check if they’re
authenticated so if I make that change
and if I go back to Chrome I’m gonna go
ahead and try to access the home route
because I’m not authenticated as you can
see I got redirected to login and in
fact I’m gonna put the same level of
protection to the logout route even
though it’s a post it only makes sense
to log out if you are in fact already
authenticated so if you’re not attending
cated you should be redirected to login
we’re gonna do something similar for
other routes in this case we’re gonna
call this middleware to redirect home
and the idea here is the one to check if
the user is authenticated in fact if
they are we want to redirect them to the
home routes to the dashboard and if
they’re not authenticated we’re gonna go
ahead and proceed with the normal
request lifecycle so this middle room
makes sense to be applied to the login
page so what this means is that if the
users were already logged in it doesn’t
make sense to show them the login form
if they try to access the login form
they’re gonna be redirected to home
because they’re already logged in same
thing for register and I’m also gonna
apply the same thing for the to pull
sprouts so slash login again only makes
sense to login to the app if you’re not
authenticated only makes sense to create
a new user if you’re not already
authenticated as well so we’re gonna go
ahead and put that protection layer as
well so for the login route we’re gonna
do is we’re gonna extract the email as
well as password from request body like
this because we’ve set up body parser we
should now be able to access them from
our request object so we can go ahead
and put some very simple validation
we’re just gonna check if the email and
password was provided of course you
could do more sophisticated validation
but this is gonna do for now so we’re
gonna try to find a user you already
have the users collection so we can call
a fine method on that array we’ll pass
any callback so if the user dot email
matches the email provided by the user
and if the user password also matches
the password so in fact if we get a user
object out of that check that means that
we can actually go ahead and put a user
ID to the session object so this is the
user ID we’re gonna rely
we’re gonna assign it to user ID so
we’re doing here is we’re trying to find
a user that matches the email address on
the request and also matches the
password on the request as well of
course this is a very simple application
and on a real site you would actually
want to of course compare the password
so you wouldn’t actually need to hash
them first only way to do but for this
tutorial just should be fine and if we
are able to find a user or gonna do is
we’re gonna take that users ID once
again in this case this could be one if
you are logging in as Alex this will be
2 or 3 depending on whose email you’re
trying to use and if the email and
password it’s both match we find the
user and we set the user ID on this
session object this is actually the user
ID that we’re gonna use throughout the
app as you can see we check against the
user ID here before redirecting to login
same thing here before we direct into
home as well as on the main page when we
decide which set of links we want to
display so this should be good for now
and then the last thing we’re gonna do
is we’re gonna redirect to slash home so
if you are authenticated this is gonna
create a session ID cookie and in the
end we’re gonna redirect to the slash
home route and if they validation failed
or if we couldn’t find the user what
we’re gonna do is we’re gonna redirect
back to the login form as well we’re
gonna do a similar thing for the
registration page so let me go ahead and
paste the same statement in this case
we’re gonna have a name as well as email
and password so if we have a name and we
also have an email as well as password
and of course I’m gonna leave a to-do
because in this case we want to keep it
simple but in a real application you
would want to do a more sophisticated
validation in fact the same thing
probably also applies here as well
because you want to verify the length of
the email the length and also the
strength of the password we’re gonna
keep it simple as I said so once we
verify those three we’re gonna try to
find if the user already exists in the
array so what we can do in this case we
can call the find method but because in
this case we only care if the user can
be found in the array so we don’t
actually care about the underlying
object we just want to make sure if it
exists we can go ahead and use the sum
method and this is gonna verify if it
can find a matching user so we’re gonna
have a user object we’re gonna compare
the email and if the email is already
taken that
means that the user already exists so if
the user doesn’t exist we’re gonna go
ahead and create a new user object so
we’ll have an ID the ID could be users
dot length increment it by one because
at the beginning we have three users and
the ID begins at index one so if we have
three users the next user will have an
ID of index four so we need to take the
length of the array and add one to it
we’re also going to have a name email
and password once again this needs to be
hashed I’m just gonna leave it to do for
future but once we have a user we can do
users dot push user this is gonna add
the user to the users collection or in
this case array and of course I’m also
going to leave a note at the top over
here in this case for this tutorial a
simple array will do but in an actual
application of course you’re gonna have
to wire it up to an actual database like
Mongo or Postgres but for now we’re
gonna push the user to the array we’re
also going to set the user ID on the
session object course this will be user
dot ID like this and finally we could
also do a return of R as dot redirect to
the home page like this in this case I’m
putting a return because I wanted to
terminate the request at this point so I
don’t want to go outside EF but in this
case if any validation fails or if the
user already exists we’re just simply
gonna do a res redirect to slash
register page of course what you could
do as well as you could also provide an
error through query string parameters so
for example you could do something like
it redirects to slash register with an
error key that could be something like
error dot auth dot user exists’ or
something like that or for example this
could be email to short you get the idea
where of course you could also flash the
error through this session but in this
case I’m just gonna leave wait to do for
query string errors this is something
you could implement on the side but this
should be good for now and now for the
logout what we’re gonna do in this case
is we already know that the user is
authenticated to the system so we’re
gonna go ahead and call request session
destroy’ once again I think I mentioned
this method before it’s actually a
that you can call so we can go ahead and
call it passing in a callback with an
error in this case I don’t think it’s
common for an error to occur but if for
some reason we couldn’t destroy this
session we’re just gonna have a redirect
so we’re gonna do return rest that
redirect to the home page so that can we
try to log out again otherwise we’re
gonna want to clear out the cookies so
what we can do is we can call response
clear cookie the cookie name in this
case is session name this is why I was
useful to extract that name to a
constant so we can go ahead and reuse
that constant for the middleware as well
as in our custom method in here so we’re
gonna clear out the cookie and once the
cookie was destroyed we’re gonna do a
res redirect to slash login page so they
can log in again if they want to so
let’s see if the application works I’m
gonna go back to the browser we can go
ahead and visit a register page or we
can log in already I’m gonna try to put
in alex at gmail.com I’m gonna put in
password I know for a fact that this is
a wrong password as you can see the page
gets refreshed so let me try again Alex
at gmail.com I’m gonna put in secret
which is the actual password and as you
can see we get logged in and I’m gonna
save it the last thing I think we forgot
is to display the name and the email of
the user and so what we can do here is
we can actually try to extract the user
from the request object so we can go
ahead and find the user so let’s to
users dot find user we’re gonna find the
user by ID so if the ID matches request
dot session dot user ID and once we have
the user we can actually go ahead and
output
user dot name and we’ll do the same
thing for the email as well now in this
case we only need to access the user
once but if you had other routes so for
example we had a route to settings or
for example slash profile and you wanted
to get access to the user in there so
you had your request and response object
if we’re gonna use that same logic it’s
going to be duplicated for every route
that needs to have access to the user
object so in cases like this it might
make sense to actually create another
middleware what we can do is we can
create a custom it over so we can call
app dot use we’re gonna pass in request
response and next
what we can do in this case is we can
have a function it’s going to try to get
the user ID from the session so request
that session as you remember the user ID
indicates whether the users logged into
the system so if we have a user ID and
by the way this check is valid because
the smallest user ID will be one it’s
never going to be zero so this check
will not fail but in most cases once
again it’s going to be an actual
database so there should be no concern
at this point so if we have a user ID
what we can do is we can use
Razzles and this is a special object
that’s going to be shared among the
middleware so we can go ahead and put
custom data into that object to be
assured between different functions and
middleware so we can go ahead and create
a user object and we can go ahead and
extract this logic for finding a user by
user ID we can go ahead and put it in
here and once again in this case we’re
checking against user ID from session so
if we were able to find a user we’re
gonna set it to res dot locals and
finally we need to call next on it so
this is gonna execute before any routes
for every single request and if that
request is authenticated if we have a
user in these session and we have a
valid session cookie ID we’re gonna find
the user by the ID and we’re going to
inject it to rest out locals so now once
we do that we can actually extract the
user from rest dot locals so we can use
a bit of destructuring here so the
reason that this syntax is useful is
because if you have more routes where
you need to access the user all you have
to do is you need to extract that user
from R as locals and of course if you
need to make sure that the user is
authenticated you could also use the
redirect login middleware so you could
actually put it in here as well and this
is gonna make sure that the user is
logged in if they’re not they’re gonna
be redirected back to the login page so
this is just an example for an extra
route if you want to add it yourself in
this case I’m just gonna keep it simple
we’re gonna have a home route so let me
go back to the home page what happens is
all of these sessions are being stored
in memory what that means is that
they’re gonna be stored as objects in
the server memory as I mentioned before
there’s an implementation for Redis
Mongo firebase if you wanted to actually
persist them to an actual storage you
could go ahead and connect it to a Redis
store in fact there’s a
very cold connect Redis it’s very simple
to set up all you need to do is you need
to install it as a dependency and when
you configure it all you have to do is
you need to pass in a host a port as
well as the password as you see over
here there’s a few other options you
could also provide but these are the
most basic ones so it’s very simple to
configure I’m not going to do it for the
time being so if I go back to my
application over here I’m going to login
with the same credentials as you can see
I get named Alex Alex at gmail.com it’s
because I’m already logged in but what
I’m gonna do is I’m gonna clear out the
cookie using this useful extension it’s
called edit this cookie so as you can
see here we get a session ID cookie and
what I’m gonna do is I’m gonna delete it
refresh they try to log in as Mac’s at
gmail.com once again I’ll try
gibberish passport it’s going to fail
but if I try again
so me to max at gmail.com we’re gonna
pass secret we get logged in once again
I’m gonna clear out the cookie what we
can do next is we can go ahead and try
to register so I’m gonna pass a name so
let’s say Susan so be Susan at gmail.com
and we’ll pass an password like this so
we get logged in if I clear out the
cookie myself i refresh as you can see I
get redirected to the login page and now
I’ll try Susan at password and I get
logged in as you can see I get Susan
Susan at gmail.com and if I go to the
main page and if I click on logout this
will log me out and once again I can log
back in with Susan at gmail.com password
can save it and I’m back to the home
page now if I go back to the editor we
can go back to the home route not just
quickly do a console log on request
session so this is gonna log us out so
I’ll have to log in again and this is
also going to delete Susan so I won’t be
able to log in again because that array
was destroyed and now we’re back to
three users again I’m trying to log in
with Alex so if we look at the terminal
as you can see we get this cookie object
but we also get the user ID set to one
of course this will differ depending on
the user who’s logged into the system so
if I try max instead I’m locked in as
Max and you can see that now we get to
user ID two and we get the actual cookie
so you can see that it’s going to expire
on
November 11 at this time in UTC so in
fact it’s currently 241 p.m. in Canada
I’m located in eastern standard time
zone so that means minus five from GMT
or UTC so that means in London it’s
currently 7 p.m. because we’re setting
the lifetime of the cookie to two hours
that means that it’s going to expire at
9 p.m. in London but of course I’m in
Montreal if I work at the cookie you can
see that in local time it’s actually
going to expire around 4:40 p.m. but
using this handful extension you could
also see that this cookie is HTTP only
in production it’s also going to be
secure and because we have a custom
expiration time of two hours you don’t
see session but if it didn’t provide the
maximum age option you would also see
this checkbox checked that means that
the cookie is session cookies so it’s
going to be cleared out as soon as the
client closes the browser and we have
things like domain set to localhost and
we also get the path the last thing I’m
gonna show you is I’m gonna switch back
to visual studio code I’m going to
console log in the request session ID
this is in fact an alias to session ID
camelcase like this and of course all
that information you could find in the
repo itself so for instance you can look
for session ID it’s another way to
access the ID of your session but I’m
going to save this file for the time
being let me go back to the application
and I’m gonna clear out the cookie I’m
gonna log in again and back in the
terminal as you can see we get this
value I’m actually gonna go ahead and
copy it so if I go back to the browser
and I open the console so if you
remember this was the session ID I’m
gonna put that string in there and I’m
also gonna copy the value of the cookie
and I paste it in over here as you can
see that cookie begins with s percentage
3 capital a so in fact this one is a URL
encoded value so we get to decode your I
component on that value and you’re gonna
see that it’s actually a value that
stands for ass Colin so after ass column
you’re gonna see that we get the session
ID up to the period and of course after
the period we get the actual signature
of the cookie once again I grabbed it
using the extension of course you won’t
be able to access the cookie using
document cookie because the cookies
server-side so you won’t be able to get
it using javascript
and once again that’s because of the
HTTP only attribute but because I’m
using this extension I’m able to still
access the value myself so I pasted it
over here and once again it begins with
s colon which is URL encoded we get the
session ID itself as you can see it
matches exactly the one in the terminal
this one will be the same for every
route as long as you’re authenticated as
the same user and also we get the
signature portion over here then this
one we use it to verify the authenticity
and integrity of the cookie and of
course this value is obtained when
assigning the cookie using the secret
which we provided in the config over
here in this case it’s a dummy string
but of course once again in an actual
application
it’ll be a strong value so this is
basically it for authentication once
again there’s a bunch of to do is that I
left of course we used a simple
collection of users in a real
application you’ll be using a database
like Mongo or Postgres the other thing
is that you would also want to enable
HTTPS you would need to do some extra
configuration on the Express nodejs side
to enable TLS connections to your server
other than that you also need to make
sure to do proper validation for your
input you also of course need to hash
the passwords we store them in plaintext
for simplicity every user has a password
of secret but that’s religious for demo
purposes of course in an actual
application you would need to hash those
passwords so you could use something
like decrypt and decrypt has useful
methods to hash passwords and also
compare them against the existing cache
that you would store in the database so
you should of course never store
plaintext passwords in the database but
that’s a given and of course you could
also implement some kind of error
reporting so for example you could flash
errors to the session so you could
display them back on your front-end you
could also pass the errors as a query
string of course you could also instead
of using these hard-coded strings you
could also use a templating engine like
bug for example or Hamel and finally
would also make sense to implement a CSR
protection so even though we’re using
the same set attribute it’s only been
introduced in recent years and the older
browsers don’t have support for it so I
would recommend to still implement CSRF
for a good protection against those
kinds of attacks and of course with
regards to the store that
you will be using for your sessions so
far we’ve been using the in-memory store
and it’s good enough for demonstration
purposes but once again as I mentioned
before you would probably need to go
back to this package over here and you
would need to look into the different
session storage mechanisms and options
that you could consider probably the
easiest one to get started with would be
the connect Redis one but once again
this is something you would need to do
for the actual application when
considering a deployment to an actual
production system but as far as the
authenticated portion that should
basically be it so this has been
authentication using session Express
library so if you enjoyed the tutorial
let me know if you have any questions
down below in the comment section but
this is it for this video
so if you found it helpful and I’m gonna see you next time take care

Please follow and like us: