elysiajs / elysia-jwt

Plugin for Elysia for using JWT Authentication
MIT License
41 stars 16 forks source link

Not able to pass exp to sign function #25

Open jeremyw189 opened 7 months ago

jeremyw189 commented 7 months ago

It would be nice to be able to pass custom expiration times when generating new tokens (a gateway app that generates tokens for multiple APIs, for example).

Current:

if (exp)
    jwt = jwt.setExpirationTime(exp);

Suggestion:

if (exp ?? morePayload.exp)
    jwt = jwt.setExpirationTime(morePayload.exp ?? exp);

That way the provided expiration time overrides the default expiration time defined in the constructor, if provided.

Example:

import { Elysia } from 'elysia';
import { jwt } from '@elysiajs/jwt';

const app = new Elysia();

// Default JWT expiration is 1 hour.
app.use(jwt({ name: 'jwt', secret: Bun.env.MY_JWT_SECRET!, exp: '1hr' }));

app.get('/sign/:name', async (context: any) => {
  // Default, 1 hour expiration.
  context.setCookie('auth', await context.jwt.sign(context.params), {
    httpOnly: true,
  });

  return `Sign in as ${context.params.name}`;
});

app.get('/sign-longer/:name', async (context: any) => {
  // 24 hour expiration.
  context.setCookie('auth', await context.jwt.sign({ ...context.params, exp: '24hr' }), {
    httpOnly: true,
  });

  return `Sign in as ${context.params.name}`;
});

app.listen(3000);
console.log(
  `🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
);
tonyeherrera commented 5 months ago

Good idea. Would love to see this implemented.

lillorme commented 5 months ago

This should definately get done. Looking forward to you guys implementing this feature soon.

grasilife commented 1 week ago

我也需要