Next.js Discord

Discord Forum

[next-auth] Authorization with separate api

Answered
Largehead hairtail posted this in #help-forum
Open in Discord
Largehead hairtailOP
I'm using next-auth with a separate API (nestjs) to create a simple avatar upload system, and I want to implement authorization in this API to prevent users from changing someone else's avatar.
My initial idea was to send the cookies in the request and validate the token in a Guard using JWT in nestjs. However, after testing and researching, I found out this isn't possible because next-auth generates a token that the JWT library doesn't recognize.
Any ideas on how to work around this?

I tried to install next-auth in the nestjs api and validate the token using the decode method of next-auth/jwt, but also without success (it ends up generating another error)
Answered by Largehead hairtail
It worked with this hack: https://www.memfree.me/blog/decrypt-verify-authjs-jwt-token
until I find a better solution it will stay like this

If anyone has a better idea to suggest 🙏
View full answer

14 Replies

Largehead hairtailOP
I still need help
Willow shoot sawfly
I think next-auth uses jose for JWT

https://www.npmjs.com/package/jose

Have you tried using this package?

What's the error you are getting?
Largehead hairtailOP
Do you have any idea how to verify the token using this? I tried all the verification methods but it didn't work, I must be doing something wrong
JWSInvalid: Invalid Compact JWS
Largehead hairtailOP
Willow shoot sawfly
Mmm it can be a few things, can you share the repo?

JWSInvalid: Invalid Compact JWS typically indicates that the token string or verification parameters do not match the expected format or algorithm for a JSON Web Signature.

If your secret is a Base64 or hexadecimal string, you might need to convert it differently rather than using TextEncoder.encode
import { decode as base64Decode } from 'base64-arraybuffer'; // or something like this
const secretBinary = new Uint8Array(base64Decode(secretBase64));


I think you could also try with jsonwebtoken library.
    const payload = jwt.verify(token, secret, { algorithms: ['HS512'] });
Largehead hairtailOP
The code isn't on github
If I send you the token and secret key, can you test it?
With jsonwebtoken returns this error: JsonWebTokenError: jwt malformed
Largehead hairtailOP
It worked with this hack: https://www.memfree.me/blog/decrypt-verify-authjs-jwt-token
until I find a better solution it will stay like this

If anyone has a better idea to suggest 🙏
Answer
Willow shoot sawfly
Cool! It looks like it was the missing part.

You could use a new service to manage your authentication like
https://github.com/openauthjs/openauth
Largehead hairtailOP
I was really looking for an alternative to NextAuth that's more practical to implement with an external API
I'll check this one out
Thanks 🤙