DEV Community

Discussion on: Authentication and Sessions for MVC Apps with NestJS

Collapse
 
rafaelsofizadeh profile image
Rafael Sofi-zada • Edited

I'm in the same situation right now. I followed the documentation, built the JWT auth system, knowing nothing about authorization, but having heard JWT used everywhere. Started reading about authorization, sessions, realized that stateless authorization isn't applicable to my use case at all. I wish there was more information on stateful authorization with Nest.js.

I suggest you to read the blog post and linked, and its follow-up.

Collapse
 
ozzythegiant profile image
Oziel Perez

@joaquimley and @rafaelsofizadeh The JWT implementation from the nest documentation is actually more of an example of how to authenticate using JSON Web Tokens as opposed to sessions. There's been a lot of debate over the years as to whether JWT is appropriate, let alone secure for Single Page Apps. To cut through the chase, if you're building a traditional site (a web app with multiple pages which cause the browser to refresh when navigating) or a Single Page App, just stick to using Sessions. If you're building a public REST API or a mobile app with a backend service, then JWT might be more useful, and even then, according to some experts, it's better to have one app handle authentication only while keeping other apps separate.

I'm assuming you're both building traditional or single-page apps, so in your case, the documentation doesn't explicitly tell you how to set up authentication along with sessions. Here's what I recommend: follow the docs on Authentication all the way down until you finish setting up your Local Guard based on AuthGuard from @nestjs/passport. The next section is JWT, so ignore all of that. Instead, follow the instructions on how to set up sessions on express, so you will need this article. This means attaching and configuring session and passport on the bootstrap function, then setting up your serializer, like the article mentions, and finding a session Store to replace the development store that express-session comes with. In my case, I'm building a custom one that implements the Store interface but you may want to look for one in the express-session docs. Hope this helps!