Reputation: 17118
I am in a conundrum.
I started out building a good old fashioned REST API todo server using NestJS. Then I added Auth0 to it using this article which has you use AuthGuard
:
https://auth0.com/blog/developing-a-secure-api-with-nestjs-adding-authorization/
However, I was never able to get things working correctly, always getting a 401 Unauthorized
error. It was frustrating.
Then I found this article:
https://auth0.com/blog/full-stack-typescript-apps-part-1-developing-backend-apis-with-nestjs/
that had me build middleware to authenticate with Auth0 and JWT. And lo and behold, it worked.
But it feels wrong -- I feel like I should be able to do the whole authorization thing with @UseGuards
and AuthGuard
and all that NestJS decorator goodness.
So I guess my question is two-fold: Am I wrong to be hesitant to use middleware over the NestJS decorator stuff? and Does anyone have a working, simple example of using the decorator stuff in NestJS?
Upvotes: 5
Views: 9955
Reputation: 11
from the Doc ....
Guards have access to the ExecutionContext instance, and thus know exactly what's going to be executed next.
middleware, It doesn't know which handler will be executed after calling the next() function.
Upvotes: 1
Reputation: 13644
It is a bit opinion-based, however, a big part of it is in the docs and is recommended good practice, so I will try to answer.
I would strongly recommend going with @Guard
. NestJS is using decorators for almost everything. Is it opinionated for sure, but it is somehow based on Spring which is used all over the world. Decorators make the code pretty verbose as you can clearly see what is applicable to either class or particular method.
I had never had an issue with e.g. JWT Guards in NestJS.
Take a look here: https://docs.nestjs.com/techniques/authentication#implementing-passport-jwt
It works like a charm for me.
Anyway - you can also try to use your custom Guard for JWT with e.g. https://github.com/auth0/node-jwks-rsa . It should be easier to debug then for sure, however, built-in JWT guard as far as I remember gives you good logs.
I would suggest to use Middleware for stuff which interacting with EACH AND EVERY response or request and Guards for all auth stuff.
Upvotes: 4