Next.js Discord

Discord Forum

Authentication system by using cookies securely.

Unanswered
Exotic Shorthair posted this in #help-forum
Open in Discord
Exotic ShorthairOP
I don't really know how to use cookies securely in an application. And how the data storing in cookies work. Can i get some examples of how to make an authentication system just by using cookies of the request header. I can take care of the data storing in Data base and all the back end stuff. Just need to know how cookies work and how to manipulate it safely

30 Replies

Exotic ShorthairOP
@Northeast Congo Lion
Northeast Congo Lion
o/
right
So my current application Portfoliize uses cookies basically by themselves for most authentication. I'll give you bits of code if you need them but it's pretty simple
You build a cookie and hash it using your internal secret key
the cookie contains info like "user ID" and "email verified" for example
this is of course stored on the client's machine along with an expiry date
you issue this cookie during key events like when the user logs in or registers, and remove it when they're done
because it's crypto secured the user won't be able to modify it
Exotic ShorthairOP
What if i want to store it on the client side and show the user their personal data based on the cookie
Like their account info
How to actually store it and give it a expiray date
Who keeps an eye on the expiray date?
Northeast Congo Lion
so yeah, the cookie will gain them ACCESS to most of the pages and stuff like that, but for getting real data you still need a helper function that collects their data (You'll need to hit the database for that). I usually have a function called userDataFromCookies which does exactly that.
@Exotic Shorthair How to actually store it and give it a expiray date
Northeast Congo Lion
I'll send some code in a second
@Exotic Shorthair Who keeps an eye on the expiray date?
Northeast Congo Lion
the browser and your backend will delete the cookie if/when it expires
export async function setCookie(res:any, value:string, ageHours:number): Promise<NextResponse> {
    const token = await new SignJWT({val:value})
      .setProtectedHeader({ alg: 'HS256' })
      .setJti(nanoid())
      .setIssuedAt()
      .setExpirationTime(`${Math.round(ageHours)}h`)
      .sign(new TextEncoder().encode(get_token_key()))
    res.setHeader("Set-Cookie", serialize("authToken", token, {
      httpOnly: true,
      maxAge: 60 * 60 * Math.round(ageHours), // 2 hours in seconds
      path: "/",
      sameSite: "strict",
    }))
    
    return res
}
Exotic ShorthairOP
What is SignJWT?
Northeast Congo Lion
import { JWTPayload, SignJWT, jwtVerify } from 'jose'
Exotic ShorthairOP
Ahh libraries
Northeast Congo Lion
the argument in signJWT is the string you want to store
yes 🙂
there's also the verifyAuth function which goes into the middleware and is executed every time the user makes any navigation:
export async function verifyAuth(req: NextRequest) {
    if (!req.cookies.get){
      //for some reason the cookie .get function isn't always defined.
      // this creates it if it's not defined.
      req.cookies.get = function (key:string) {
          let foundVal:any = req.cookies[key as keyof typeof req.cookies]
          let cookieFound:any = {value: foundVal, name: key}
          return cookieFound
      }
    }
    
    const token = req.cookies.get("authToken")?.value

    if (!token) return undefined

    try {
      const verified = await jwtVerify(
        token,
        new TextEncoder().encode(get_token_key())
      ) 
      const verifiedPayloadJWT = verified.payload as JWTPayload
      return verifiedPayloadJWT
    } catch (err) {
      return undefined
    }
  }
Exotic ShorthairOP
Okay these looks promising..
Also I read in the docs that Next.js has extended support for cookies
So does it mean we can accomplish the same thing in next.js without using the JWT libraries
I mean i can encrypt with bcrypt or something and store the data right?
Northeast Congo Lion
Probably, I never had any luck with anything other than Jose
Northeast Congo Lion
kk