Authentication with Session
Session
After request is finished, the server will forget who we are.
With session, the server gives us session id and all session id data is stored in session DB
$Ad : Traditional and much secure than JWT
Dis : You need more DB so it comes with Redis for this case. If you work with mongoDB, there’s a library called “connect-mongo”. The session data is stored in a separate MongoDB collection
JWT
JWT is a token way. JWT the server put info in token itself. The server will just verify signature.
Passport
Its Node.js middleware to authenticate user.
Passport + jwt
Passport + session
yarn add passport passport-local
passport
: Core of passport packagepassport-local
: Your own to implement yourself
passport/local.js
module.exports = () => {
passport.use(
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
},
(email, password, done) => {}
)
);
};
usernameField
is an option to check the ID of the user that passport will readpasswordField
is an option to check the user’s password.
This function receives three parameters as user ID, password, and a function called done to call the result of authentication.
To save passport data, it comes session.
yarn add express-session cookie-parser
app.use(cookieParser());
app.use(session());
app.use(passport.initialize());
app.use(passport.session());
Why we need cookies and sessions:
Browser and server require the same login data because each uses a different server(domain).
Now the server decides its me or not with cookie
Differences between Session vs token?
- In Session way, it is written with simple text and compare in session DB. it requires to compare session DB every time
2. In JWT way, it contains so many data. Once its verified, it is fast. But it is so easy decode.
Cookie === transportation system
Token === a very werid long string
JWT === Token system that self contained infomation without need DB
In FE,
axios.defaults.withCredentials = true;
In BE,
app.use(cors({
origin: true,
credentials: true,
};));
Now my app is able to share cookies between FE and BE
// Create a post
router.post("/", isLoggedIn, async (req, res) => {
// const currentUser = await User.findById(req.body.userId);
console.log((req.user._id.toString())); // Convert MongoDB's Id to string
const newPost = await Post.create({
...req.body,
userId: req.user._id.toString(),
location: {
type: "Point",
coordinates: [
parseFloat(req.body.lng),
parseFloat(req.body.lat)
],
},
});
References