Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Clerk JWT Authentication with NestJs + Passport for REST & GraphQL

Posted on Oct 18 If you're like me. You already love using Clerk to handle all Authentication for you in the Frontend.However, I recently needed to connect my NextJs+Clerk frontend with a NestJs backend. The docs do a good job explaining how to implement a Manual JWT Verification for the backend endpoints. But I couldn't find specific info on how to implement it with NestJs.Here is the solution I made using PassportJsTo connect our NestJs application with Clerk, we'll need the and the JWT public key from the Api Keys sectionCopy and save the JWT public key without the "/.well-known/jwks.json" part.We will need it to validate the JWT coming from the frontend.Let's create a new Nestjs project.I'm gonna go ahead and choose npm but u can choose any you like.Now let's create some rest endpoints.Let's go ahead and create a new endpoint called pingOne under our Controller Class.And modify our Service Class.Now lets test the endpointStart the server npm run start:devAnd test itGood! Now let's do the GraphQL EndpointYou'll also have to install these to use NestJs with GraphQL per the official documentation.And add this line to your ./app.module.tsAnd now let's repeat the process from rest-endpointsFor your Resolver ClassFor your Service ClassNow lets go to http://localhost:3000/graphql and test itGood! Now to the interesting partLet's start by creating a Nest Module for the AuthenticationPassport helps us setup our desired Authentication Strategy. We'll use the JSON Web Token (JWT) Passport Strategy to connect it with Clerk.The @nestjs/passport module helps us wrap this Strategy for NestJs.To implement the Passport Strategy, first add the JWT issuer Url we copied from our Clerk Dashboard Api Keys section to our .env file.Next you'll need to install @nestjs/config to access the env variable.Lets update our App module to use the .env file.And now we can create our Passport StrategyIn NestJS, to make a Passport Strategy, you simply extend the class you get from the PassportStrategy function, which comes from @nestjs/passport. You tell it which strategy you're using by giving it the JWT Strategy from passport-jwt.You pass the config for the strategy in the constructor via super(). This setup ensures we can decode JWT tokens and sets the API to recognize tokens with the RS256 sign.RS256 is chosen because it's a widely-accepted RSA signature-based algorithm that provides strong security by using a private key for signing and a public key for verification, ensuring the JWT wasn't altered after its creation.NestJS replaces the usual verify callback with a validate() method. But here's the cool part: Clerk does the hard part of authenticating the user. By the time validate() is called, Clerk already knows who the user is and gives you their details in the payload. Your app then attaches this to the request, so you can use it anywhere, like in controllers or middleware.The next step is to create our custom Authentication Guard that extends from Passport's AuthGuard.The JwtAuthGuard is a custom guard tailored for both REST and GraphQL in a NestJS application. It extends the default AuthGuard and specifies the 'jwt' strategy. The getRequest method part helps integrate the guard with GraphQL. When invoked, it takes the current ExecutionContext, converts it to a GraphQL-specific context using GqlExecutionContext.create, and then extracts and returns the request (req) object. This ensures that our JWT authentication works seamlessly across both RESTful routes and GraphQL queries or mutations. Lastly lets update our Authentication ModuleGood! We are done. Now lets add our custom guards to our endpoints to test them out.In our src/rest-endpoints/rest-endpoints.controller.ts we add the guard to our ping endpoint.And that's it! If we runWe'll get aBut when we add a Bearer Token from ClerkWe getIf we try it out with our GraphQL EndpointWe get the expected behaviour!And that's it! Hope this was useful. I'll be posting more about Clerk and NestJs in the coming weeks so if ur into that follow me on Twitterhttps://twitter.com/RobertoYamanakaYou can find your Clerk Bearer token under localstorage in your frontend as clerk-db-jwthttps://github.com/robertoyamanaka/clerk-w-nestjsTemplates let you quickly answer FAQs or store snippets for re-use. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well Confirm For further actions, you may consider blocking this person and/or reporting abuse Harsh Makwana - Mar 14 Rifki Andriyanto - Mar 3 Eduard Krivanek - Mar 13 Micael Levi L. C. - Mar 11 Once suspended, robertoyamanaka will not be able to comment or publish posts until their suspension is removed. Once unsuspended, robertoyamanaka will be able to comment and publish posts again. Once unpublished, all posts by robertoyamanaka will become hidden and only accessible to themselves. If robertoyamanaka is not suspended, they can still re-publish their posts from their dashboard. Note: Once unpublished, this post will become invisible to the public and only accessible to Roberto Yamanaka. They can still re-publish the post if they are not suspended. Thanks for keeping DEV Community safe. Here is what you can do to flag robertoyamanaka: robertoyamanaka consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy. Unflagging robertoyamanaka will restore default visibility to their posts. DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey. Built on Forem — the open source software that powers DEV and other inclusive communities.Made with love and Ruby on Rails. DEV Community © 2016 - 2023. We're a place where coders share, stay up-to-date and grow their careers.



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Clerk JWT Authentication with NestJs + Passport for REST & GraphQL

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×