#What is the best way to implement authentication and authorization in nestjs

5 messages · Page 1 of 1 (latest)

fickle vine
#

What is the best way to implement authentication and authorization in nestjs using mongoose, mongodb and JWT ?
I am aware of it using express.js but I am trying it in a nestjs, I have already watched many github repos and tutorials, but I want to know which is the best approach and importantly what is the best structure...

pulsar elbow
#

From my personal experience, there is no thing as best approach / best structure. You can use Passport strategies or use providers like BetterAuth, and both have their own advantages. For an easier integration I would suggest better auth, as it also handles access and refresh tokens out of the box.

knotty moth
#

I don't know if I do it correctly but that's my workflow. I don't know why people add better auth cause it adds more complexity (from the POV of a single developer).

My workflow is :
On the frontend on oauth response (with provider token and user email), I post to /verify.
On backend I check :
If user exists, if he has a current session, if oauth token is correct with the provider api.
If user exists I return the user data and redirect to authed side of the app with the auth token and create a new session in the db.
If he doesn't I onboard him and after I post to /sign-up and I return the new user along with the auth token and I create a new session in the db

On logout I get /logout along the authorization header and if there is a session and if auth token is correct I kill that session and empty the token constant on the frontend

sonic gorge
#

I've been using CASL on most project. I've yet to find something better

knotty moth