Giter VIP home page Giter VIP logo

Comments (11)

kamilmysliwiec avatar kamilmysliwiec commented on May 3, 2024 43

Refresh tokens mechanism can be easily implemented using this package. Nothing more is needed

from jwt.

Whale-Street avatar Whale-Street commented on May 3, 2024 38

Took me half a day to figure this out, so I hope this helps others.

E.g For Token Creation/Signing

  • Module
@Module({
  imports: [JwtModule.register({})], // Must register with empty options object...
})
export class SomeModule {}
  • Signing/Creation
constructor(private jwtService: JwtService){}
...
...
const payload = { userdetails: userdetails };
const accessToken = this.jwtService.sign(payload, {
  secret: accessConfig.secret, // unique access secret from environment vars
  expiresIn: accessConfig.signOptions.expiresIn, // unique access expiration from environment vars
});

const refreshToken = this.jwtService.sign(payload, {
  secret: refreshConfig.secret, // unique refresh secret from environment vars
  expiresIn: refreshConfig.signOptions.expiresIn, // unique refresh expiration from environment vars
});
...
// Store refresh **token-hash** in DB
...
// return tokens to client
return {
  accessToken: accessToken,
  refreshToken: refreshToken,
};

Eg. For Token AuthGuard Strategy

  • AuthGuard Strategy
@Injectable()
export class JwtRefreshStrategy extends PassportStrategy(
  Strategy,
  'jwt-refresh-strategy',
) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtRefreshConfig.secret, // gets secret from environment variables
    });
  }

  async validate(payload: any) {
    // DB checks for refresh token: valid, revoked, etc...
    ...
    ...
    return { username: payload.username };
  }
}

My suggested changes to this package:

  • Handle registration if JwtModule is imported but not registered with empty object.
  • Update docs to make clear that JwtModule can simply be imported, and JwtService can be passed options.

Eg. What this package should do:

@Module({
  imports: [JwtModule], // Import like any other module
})
export class SomeModule {}

...
...
// Package should have some conditional check
// Sudo code example
if(!JwtModuleRegistered) {
  JwtModule.register({});
}

from jwt.

Photon79 avatar Photon79 commented on May 3, 2024 29

Refresh tokens mechanism can be easily implemented using this package. Nothing more is needed

@kamilmysliwiec The ingenious answer. Can you show this easy implementation?

from jwt.

shamahan avatar shamahan commented on May 3, 2024 22

@shamahan Yes, but where do you refresh one?

My solution is: /auth/refresh route which accept refresh token from headers then validate by secret and check token in db. If token valid and stored in db I would recreate tokens and update refresh token in db.

from jwt.

kamilmysliwiec avatar kamilmysliwiec commented on May 3, 2024 1

@Brock-Wood Contributions to the docs are more than welcome! If you are interested, feel free to create a PR with any improvements you think might be useful 💪

from jwt.

Hagith avatar Hagith commented on May 3, 2024 1

Just for the reference, here is my VERY basic implementation: modernweb-pl/vue-nest-monorepo#32

from jwt.

shamahan avatar shamahan commented on May 3, 2024

@Photon79 You may generate two tokens one as access_token second as refresh_token with different expiresIn time.

from jwt.

mmv08 avatar mmv08 commented on May 3, 2024

@shamahan Yes, but where do you refresh one?

For me one of the possibilities seems to be implementing a custom AuthGuard which would throw a custom exception which then would be caught by exception filter

from jwt.

kamilmysliwiec avatar kamilmysliwiec commented on May 3, 2024

You can follow the same instructions with this package as it's using the jsonwebtoken under the hood.

from jwt.

Whale-Street avatar Whale-Street commented on May 3, 2024

You can follow the same instructions with this package as it's using the jsonwebtoken under the hood.

Well.... I just took a look at her again, and you obviously are correct, but man the docs should really point this out. I'll update my previous comment to reflect the correct way using this package.

Thanks!

from jwt.

gauriz avatar gauriz commented on May 3, 2024

@Brock-Wood Many thanks! ❤️

from jwt.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.