Using 'nestjs/jwt' signing with dynamic/user-related secretGetting, 'throw typeError(MSG_INVALID_SECRET);' when i run node severUnderstanding RSA signing for JWTImplementing JWT, JWE and JWS (signed JWT) with Keycloak in Spring BootIssue with retrieval of the cert/secret for JWT authentication. (Node/Express/C#/IdentityServer)NestJS jwt-passport AuthenticationGenerate a sufficient secret for JWT NodeJS LambdaWhere to store access token from external API?Invalid signature when verifying Keycloak JWT signed with EC512Auth module with deferred User moduleNestJS, MongoDB, Mongoose, GraphQL - Repeating myself describing a User or any model

We get more abuse than anyone else

Grouping into more groups in one iteration

Term “console” in game consoles

How did Jayne know when to shoot?

Operation Unzalgo

Round command argument before using

Arithmetics in LuaLaTeX

Is straight-up writing someone's opinions telling?

Practical example in using (homotopy) type theory

Amira L'Akum not on Shabbat

Is encryption still applied if you ignore the SSL certificate warning for self signed?

Everyone but three

Zhora asks Deckard: "Are you for real?" Was this meant to be significant?

Why don't humans perceive waves as twice the frequency they are?

What was the average temperature of space near the Spitzer Satellite Telescope?

How to find location on Cambridge-Mildenhall railway that still has tracks/rails?

Why is the Intel 8086 CPU called a 16-bit CPU?

What could make large expeditions ineffective for exploring territory full of dangers and valuable resources?

What were the problems on the Apollo 11 lunar module?

Should I have shared a document with a former employee?

Locked-up DOS computer beeped on keypress. What mechanism caused that?

Applying for jobs with an obvious scar

How can I duct through a new cabinet from a floor vent opening at the wall?

Why do space operations use "nominal" to mean "working correctly"?



Using 'nestjs/jwt' signing with dynamic/user-related secret


Getting, 'throw typeError(MSG_INVALID_SECRET);' when i run node severUnderstanding RSA signing for JWTImplementing JWT, JWE and JWS (signed JWT) with Keycloak in Spring BootIssue with retrieval of the cert/secret for JWT authentication. (Node/Express/C#/IdentityServer)NestJS jwt-passport AuthenticationGenerate a sufficient secret for JWT NodeJS LambdaWhere to store access token from external API?Invalid signature when verifying Keycloak JWT signed with EC512Auth module with deferred User moduleNestJS, MongoDB, Mongoose, GraphQL - Repeating myself describing a User or any model






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4















I'm trying to create a user token based on the secret of the user trying to log in. However instead of using a secret from the environment I want to use a secret assigned to a user object inside the database.



import Injectable from '@nestjs/common';
import JwtService from '@nestjs/jwt';
import UserService from '@src/modules/user/services';

@Injectable()
export class AuthService
public constructor(private readonly jwtService: JwtService,
private readonly userService: UserService)

public async createToken(email: string): Promise<JwtReply>
const expiresIn = 60 * 60 * 24;
const user = await this.userService.user( where: email );
const accessToken = await this.jwtService.signAsync( email: user.email ,
/* user.secret ,*/
expiresIn );

return
accessToken,
expiresIn,
;




I'm new to Nestjs and maybe I'm missing something.
node-jsonwebtoken does provide the necessary parameter in the sign(...) function. nestjs/jwt is missing this parameter (see code). How would you solve it without using node-jsonwebtoken or maybe a more abstract question: does my way of handling user secret make sense here? Thanks.










share|improve this question






























    4















    I'm trying to create a user token based on the secret of the user trying to log in. However instead of using a secret from the environment I want to use a secret assigned to a user object inside the database.



    import Injectable from '@nestjs/common';
    import JwtService from '@nestjs/jwt';
    import UserService from '@src/modules/user/services';

    @Injectable()
    export class AuthService
    public constructor(private readonly jwtService: JwtService,
    private readonly userService: UserService)

    public async createToken(email: string): Promise<JwtReply>
    const expiresIn = 60 * 60 * 24;
    const user = await this.userService.user( where: email );
    const accessToken = await this.jwtService.signAsync( email: user.email ,
    /* user.secret ,*/
    expiresIn );

    return
    accessToken,
    expiresIn,
    ;




    I'm new to Nestjs and maybe I'm missing something.
    node-jsonwebtoken does provide the necessary parameter in the sign(...) function. nestjs/jwt is missing this parameter (see code). How would you solve it without using node-jsonwebtoken or maybe a more abstract question: does my way of handling user secret make sense here? Thanks.










    share|improve this question


























      4












      4








      4


      1






      I'm trying to create a user token based on the secret of the user trying to log in. However instead of using a secret from the environment I want to use a secret assigned to a user object inside the database.



      import Injectable from '@nestjs/common';
      import JwtService from '@nestjs/jwt';
      import UserService from '@src/modules/user/services';

      @Injectable()
      export class AuthService
      public constructor(private readonly jwtService: JwtService,
      private readonly userService: UserService)

      public async createToken(email: string): Promise<JwtReply>
      const expiresIn = 60 * 60 * 24;
      const user = await this.userService.user( where: email );
      const accessToken = await this.jwtService.signAsync( email: user.email ,
      /* user.secret ,*/
      expiresIn );

      return
      accessToken,
      expiresIn,
      ;




      I'm new to Nestjs and maybe I'm missing something.
      node-jsonwebtoken does provide the necessary parameter in the sign(...) function. nestjs/jwt is missing this parameter (see code). How would you solve it without using node-jsonwebtoken or maybe a more abstract question: does my way of handling user secret make sense here? Thanks.










      share|improve this question
















      I'm trying to create a user token based on the secret of the user trying to log in. However instead of using a secret from the environment I want to use a secret assigned to a user object inside the database.



      import Injectable from '@nestjs/common';
      import JwtService from '@nestjs/jwt';
      import UserService from '@src/modules/user/services';

      @Injectable()
      export class AuthService
      public constructor(private readonly jwtService: JwtService,
      private readonly userService: UserService)

      public async createToken(email: string): Promise<JwtReply>
      const expiresIn = 60 * 60 * 24;
      const user = await this.userService.user( where: email );
      const accessToken = await this.jwtService.signAsync( email: user.email ,
      /* user.secret ,*/
      expiresIn );

      return
      accessToken,
      expiresIn,
      ;




      I'm new to Nestjs and maybe I'm missing something.
      node-jsonwebtoken does provide the necessary parameter in the sign(...) function. nestjs/jwt is missing this parameter (see code). How would you solve it without using node-jsonwebtoken or maybe a more abstract question: does my way of handling user secret make sense here? Thanks.







      javascript node.js typescript jwt nestjs






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 26 at 23:06









      Kim Kern

      14.2k5 gold badges42 silver badges66 bronze badges




      14.2k5 gold badges42 silver badges66 bronze badges










      asked Mar 26 at 9:50









      Tom SiwikTom Siwik

      4474 silver badges17 bronze badges




      4474 silver badges17 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          2














          This is not yet possible solely with nest's JwtModule but you can easily implement the missing parts yourself.



          Live Demo



          Edit Nest Dynamic JWT Secrets



          You can create tokens by calling the following routes:



          user1 (secret: '123'): https://yw7wz99zv1.sse.codesandbox.io/login/1


          user2 (secret: '456'): https://yw7wz99zv1.sse.codesandbox.io/login/2



          Then call the protected route '/' with your token and receive your user:



          curl -X GET https://yw7wz99zv1.sse.codesandbox.io/ 
          -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxIiwiaWF0IjoxNTUzNjQwMjc5fQ.E5o3djesqWVHNGe-Hi3KODp0aTiQU9X_H3Murht1R5U'



          How does it work?



          In the AuthService I'm just using the standard jsonwebtoken library to create the token. You can then call createToken from your login route:



          import * as jwt from 'jsonwebtoken';

          export class AuthService
          constructor(private readonly userService: UserService)

          createToken(userId: string)
          const user = this.userService.getUser(userId);
          return jwt.sign( userId: user.userId , user.secret, expiresIn: 3600 );


          // ...



          In the JwtStrategy you use secretOrKeyProvider instead of secretOrKey which can asynchronously access the UserService to get the user secret dynamically:



          export class JwtStrategy extends PassportStrategy(Strategy) 
          constructor(
          private readonly authService: AuthService,
          private readonly userService: UserService,
          )
          super(
          jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
          secretOrKeyProvider: (request, jwtToken, done) =>
          const decodedToken: any = jwt.decode(jwtToken);
          const user = this.userService.getUser(decodedToken.userId);
          done(null, user.secret);
          ,
          );


          // ...



          Note that the options you pass to the JwtModule like expiresIn will not be used, instead directly pass your options in the AuthService. Import the JwtModule without any options:



          JwtModule.register()


          General




          Does my way of handling user secret make sense here?




          This is hard to answer without knowing your exact requirements. I guess there are use cases for jwt with dynamic secrets but with it you are losing a great property of jwt: they are stateless. This means that your AuthService can issue a jwt token and some ProductService that requires authentication can just trust the jwt (it knows the secret) without making any calls to other services (i.e. UserService which has to query the database).



          If user-related keys are not a hard requirement consider rotating the keys frequently instead by making use of jwt's kid property.






          share|improve this answer

























          • This is precisely what I ended up doing (no other choise with nestjs/jwt). Except that I store the token in the user itself instead of decoding the token for the purpose of invalidating the token (in secretOrKeyProvider). Thank you for the general explanation. The staleless token argument forces me to think about it some more. Good point.

            – Tom Siwik
            Mar 27 at 8:17







          • 1





            Glad to hear. :) If it's not a hard requirement consider rotating the keys frequently instead by making use of jwt's kid property

            – Kim Kern
            Mar 27 at 8:26











          • This is a very good idea. Do you have any sources how this is used in practice I can look up? I assume this needs to be done with a secretOrKeyProvider to temporarily accept previously used secrets?

            – Tom Siwik
            Mar 27 at 9:45











          • Yep, at least for the expiration time you have to accept old keys. I haven't implemented it myself so I can't really point to a good ressource, sorry

            – Kim Kern
            Mar 27 at 11:00












          • Thanks, no problem. This small hint might be enough already. I'll try to come up with an elegant solution. Cheers

            – Tom Siwik
            Mar 27 at 11:24










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55354102%2fusing-nestjs-jwt-signing-with-dynamic-user-related-secret%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          This is not yet possible solely with nest's JwtModule but you can easily implement the missing parts yourself.



          Live Demo



          Edit Nest Dynamic JWT Secrets



          You can create tokens by calling the following routes:



          user1 (secret: '123'): https://yw7wz99zv1.sse.codesandbox.io/login/1


          user2 (secret: '456'): https://yw7wz99zv1.sse.codesandbox.io/login/2



          Then call the protected route '/' with your token and receive your user:



          curl -X GET https://yw7wz99zv1.sse.codesandbox.io/ 
          -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxIiwiaWF0IjoxNTUzNjQwMjc5fQ.E5o3djesqWVHNGe-Hi3KODp0aTiQU9X_H3Murht1R5U'



          How does it work?



          In the AuthService I'm just using the standard jsonwebtoken library to create the token. You can then call createToken from your login route:



          import * as jwt from 'jsonwebtoken';

          export class AuthService
          constructor(private readonly userService: UserService)

          createToken(userId: string)
          const user = this.userService.getUser(userId);
          return jwt.sign( userId: user.userId , user.secret, expiresIn: 3600 );


          // ...



          In the JwtStrategy you use secretOrKeyProvider instead of secretOrKey which can asynchronously access the UserService to get the user secret dynamically:



          export class JwtStrategy extends PassportStrategy(Strategy) 
          constructor(
          private readonly authService: AuthService,
          private readonly userService: UserService,
          )
          super(
          jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
          secretOrKeyProvider: (request, jwtToken, done) =>
          const decodedToken: any = jwt.decode(jwtToken);
          const user = this.userService.getUser(decodedToken.userId);
          done(null, user.secret);
          ,
          );


          // ...



          Note that the options you pass to the JwtModule like expiresIn will not be used, instead directly pass your options in the AuthService. Import the JwtModule without any options:



          JwtModule.register()


          General




          Does my way of handling user secret make sense here?




          This is hard to answer without knowing your exact requirements. I guess there are use cases for jwt with dynamic secrets but with it you are losing a great property of jwt: they are stateless. This means that your AuthService can issue a jwt token and some ProductService that requires authentication can just trust the jwt (it knows the secret) without making any calls to other services (i.e. UserService which has to query the database).



          If user-related keys are not a hard requirement consider rotating the keys frequently instead by making use of jwt's kid property.






          share|improve this answer

























          • This is precisely what I ended up doing (no other choise with nestjs/jwt). Except that I store the token in the user itself instead of decoding the token for the purpose of invalidating the token (in secretOrKeyProvider). Thank you for the general explanation. The staleless token argument forces me to think about it some more. Good point.

            – Tom Siwik
            Mar 27 at 8:17







          • 1





            Glad to hear. :) If it's not a hard requirement consider rotating the keys frequently instead by making use of jwt's kid property

            – Kim Kern
            Mar 27 at 8:26











          • This is a very good idea. Do you have any sources how this is used in practice I can look up? I assume this needs to be done with a secretOrKeyProvider to temporarily accept previously used secrets?

            – Tom Siwik
            Mar 27 at 9:45











          • Yep, at least for the expiration time you have to accept old keys. I haven't implemented it myself so I can't really point to a good ressource, sorry

            – Kim Kern
            Mar 27 at 11:00












          • Thanks, no problem. This small hint might be enough already. I'll try to come up with an elegant solution. Cheers

            – Tom Siwik
            Mar 27 at 11:24















          2














          This is not yet possible solely with nest's JwtModule but you can easily implement the missing parts yourself.



          Live Demo



          Edit Nest Dynamic JWT Secrets



          You can create tokens by calling the following routes:



          user1 (secret: '123'): https://yw7wz99zv1.sse.codesandbox.io/login/1


          user2 (secret: '456'): https://yw7wz99zv1.sse.codesandbox.io/login/2



          Then call the protected route '/' with your token and receive your user:



          curl -X GET https://yw7wz99zv1.sse.codesandbox.io/ 
          -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxIiwiaWF0IjoxNTUzNjQwMjc5fQ.E5o3djesqWVHNGe-Hi3KODp0aTiQU9X_H3Murht1R5U'



          How does it work?



          In the AuthService I'm just using the standard jsonwebtoken library to create the token. You can then call createToken from your login route:



          import * as jwt from 'jsonwebtoken';

          export class AuthService
          constructor(private readonly userService: UserService)

          createToken(userId: string)
          const user = this.userService.getUser(userId);
          return jwt.sign( userId: user.userId , user.secret, expiresIn: 3600 );


          // ...



          In the JwtStrategy you use secretOrKeyProvider instead of secretOrKey which can asynchronously access the UserService to get the user secret dynamically:



          export class JwtStrategy extends PassportStrategy(Strategy) 
          constructor(
          private readonly authService: AuthService,
          private readonly userService: UserService,
          )
          super(
          jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
          secretOrKeyProvider: (request, jwtToken, done) =>
          const decodedToken: any = jwt.decode(jwtToken);
          const user = this.userService.getUser(decodedToken.userId);
          done(null, user.secret);
          ,
          );


          // ...



          Note that the options you pass to the JwtModule like expiresIn will not be used, instead directly pass your options in the AuthService. Import the JwtModule without any options:



          JwtModule.register()


          General




          Does my way of handling user secret make sense here?




          This is hard to answer without knowing your exact requirements. I guess there are use cases for jwt with dynamic secrets but with it you are losing a great property of jwt: they are stateless. This means that your AuthService can issue a jwt token and some ProductService that requires authentication can just trust the jwt (it knows the secret) without making any calls to other services (i.e. UserService which has to query the database).



          If user-related keys are not a hard requirement consider rotating the keys frequently instead by making use of jwt's kid property.






          share|improve this answer

























          • This is precisely what I ended up doing (no other choise with nestjs/jwt). Except that I store the token in the user itself instead of decoding the token for the purpose of invalidating the token (in secretOrKeyProvider). Thank you for the general explanation. The staleless token argument forces me to think about it some more. Good point.

            – Tom Siwik
            Mar 27 at 8:17







          • 1





            Glad to hear. :) If it's not a hard requirement consider rotating the keys frequently instead by making use of jwt's kid property

            – Kim Kern
            Mar 27 at 8:26











          • This is a very good idea. Do you have any sources how this is used in practice I can look up? I assume this needs to be done with a secretOrKeyProvider to temporarily accept previously used secrets?

            – Tom Siwik
            Mar 27 at 9:45











          • Yep, at least for the expiration time you have to accept old keys. I haven't implemented it myself so I can't really point to a good ressource, sorry

            – Kim Kern
            Mar 27 at 11:00












          • Thanks, no problem. This small hint might be enough already. I'll try to come up with an elegant solution. Cheers

            – Tom Siwik
            Mar 27 at 11:24













          2












          2








          2







          This is not yet possible solely with nest's JwtModule but you can easily implement the missing parts yourself.



          Live Demo



          Edit Nest Dynamic JWT Secrets



          You can create tokens by calling the following routes:



          user1 (secret: '123'): https://yw7wz99zv1.sse.codesandbox.io/login/1


          user2 (secret: '456'): https://yw7wz99zv1.sse.codesandbox.io/login/2



          Then call the protected route '/' with your token and receive your user:



          curl -X GET https://yw7wz99zv1.sse.codesandbox.io/ 
          -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxIiwiaWF0IjoxNTUzNjQwMjc5fQ.E5o3djesqWVHNGe-Hi3KODp0aTiQU9X_H3Murht1R5U'



          How does it work?



          In the AuthService I'm just using the standard jsonwebtoken library to create the token. You can then call createToken from your login route:



          import * as jwt from 'jsonwebtoken';

          export class AuthService
          constructor(private readonly userService: UserService)

          createToken(userId: string)
          const user = this.userService.getUser(userId);
          return jwt.sign( userId: user.userId , user.secret, expiresIn: 3600 );


          // ...



          In the JwtStrategy you use secretOrKeyProvider instead of secretOrKey which can asynchronously access the UserService to get the user secret dynamically:



          export class JwtStrategy extends PassportStrategy(Strategy) 
          constructor(
          private readonly authService: AuthService,
          private readonly userService: UserService,
          )
          super(
          jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
          secretOrKeyProvider: (request, jwtToken, done) =>
          const decodedToken: any = jwt.decode(jwtToken);
          const user = this.userService.getUser(decodedToken.userId);
          done(null, user.secret);
          ,
          );


          // ...



          Note that the options you pass to the JwtModule like expiresIn will not be used, instead directly pass your options in the AuthService. Import the JwtModule without any options:



          JwtModule.register()


          General




          Does my way of handling user secret make sense here?




          This is hard to answer without knowing your exact requirements. I guess there are use cases for jwt with dynamic secrets but with it you are losing a great property of jwt: they are stateless. This means that your AuthService can issue a jwt token and some ProductService that requires authentication can just trust the jwt (it knows the secret) without making any calls to other services (i.e. UserService which has to query the database).



          If user-related keys are not a hard requirement consider rotating the keys frequently instead by making use of jwt's kid property.






          share|improve this answer















          This is not yet possible solely with nest's JwtModule but you can easily implement the missing parts yourself.



          Live Demo



          Edit Nest Dynamic JWT Secrets



          You can create tokens by calling the following routes:



          user1 (secret: '123'): https://yw7wz99zv1.sse.codesandbox.io/login/1


          user2 (secret: '456'): https://yw7wz99zv1.sse.codesandbox.io/login/2



          Then call the protected route '/' with your token and receive your user:



          curl -X GET https://yw7wz99zv1.sse.codesandbox.io/ 
          -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxIiwiaWF0IjoxNTUzNjQwMjc5fQ.E5o3djesqWVHNGe-Hi3KODp0aTiQU9X_H3Murht1R5U'



          How does it work?



          In the AuthService I'm just using the standard jsonwebtoken library to create the token. You can then call createToken from your login route:



          import * as jwt from 'jsonwebtoken';

          export class AuthService
          constructor(private readonly userService: UserService)

          createToken(userId: string)
          const user = this.userService.getUser(userId);
          return jwt.sign( userId: user.userId , user.secret, expiresIn: 3600 );


          // ...



          In the JwtStrategy you use secretOrKeyProvider instead of secretOrKey which can asynchronously access the UserService to get the user secret dynamically:



          export class JwtStrategy extends PassportStrategy(Strategy) 
          constructor(
          private readonly authService: AuthService,
          private readonly userService: UserService,
          )
          super(
          jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
          secretOrKeyProvider: (request, jwtToken, done) =>
          const decodedToken: any = jwt.decode(jwtToken);
          const user = this.userService.getUser(decodedToken.userId);
          done(null, user.secret);
          ,
          );


          // ...



          Note that the options you pass to the JwtModule like expiresIn will not be used, instead directly pass your options in the AuthService. Import the JwtModule without any options:



          JwtModule.register()


          General




          Does my way of handling user secret make sense here?




          This is hard to answer without knowing your exact requirements. I guess there are use cases for jwt with dynamic secrets but with it you are losing a great property of jwt: they are stateless. This means that your AuthService can issue a jwt token and some ProductService that requires authentication can just trust the jwt (it knows the secret) without making any calls to other services (i.e. UserService which has to query the database).



          If user-related keys are not a hard requirement consider rotating the keys frequently instead by making use of jwt's kid property.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 27 at 11:06

























          answered Mar 26 at 22:50









          Kim KernKim Kern

          14.2k5 gold badges42 silver badges66 bronze badges




          14.2k5 gold badges42 silver badges66 bronze badges












          • This is precisely what I ended up doing (no other choise with nestjs/jwt). Except that I store the token in the user itself instead of decoding the token for the purpose of invalidating the token (in secretOrKeyProvider). Thank you for the general explanation. The staleless token argument forces me to think about it some more. Good point.

            – Tom Siwik
            Mar 27 at 8:17







          • 1





            Glad to hear. :) If it's not a hard requirement consider rotating the keys frequently instead by making use of jwt's kid property

            – Kim Kern
            Mar 27 at 8:26











          • This is a very good idea. Do you have any sources how this is used in practice I can look up? I assume this needs to be done with a secretOrKeyProvider to temporarily accept previously used secrets?

            – Tom Siwik
            Mar 27 at 9:45











          • Yep, at least for the expiration time you have to accept old keys. I haven't implemented it myself so I can't really point to a good ressource, sorry

            – Kim Kern
            Mar 27 at 11:00












          • Thanks, no problem. This small hint might be enough already. I'll try to come up with an elegant solution. Cheers

            – Tom Siwik
            Mar 27 at 11:24

















          • This is precisely what I ended up doing (no other choise with nestjs/jwt). Except that I store the token in the user itself instead of decoding the token for the purpose of invalidating the token (in secretOrKeyProvider). Thank you for the general explanation. The staleless token argument forces me to think about it some more. Good point.

            – Tom Siwik
            Mar 27 at 8:17







          • 1





            Glad to hear. :) If it's not a hard requirement consider rotating the keys frequently instead by making use of jwt's kid property

            – Kim Kern
            Mar 27 at 8:26











          • This is a very good idea. Do you have any sources how this is used in practice I can look up? I assume this needs to be done with a secretOrKeyProvider to temporarily accept previously used secrets?

            – Tom Siwik
            Mar 27 at 9:45











          • Yep, at least for the expiration time you have to accept old keys. I haven't implemented it myself so I can't really point to a good ressource, sorry

            – Kim Kern
            Mar 27 at 11:00












          • Thanks, no problem. This small hint might be enough already. I'll try to come up with an elegant solution. Cheers

            – Tom Siwik
            Mar 27 at 11:24
















          This is precisely what I ended up doing (no other choise with nestjs/jwt). Except that I store the token in the user itself instead of decoding the token for the purpose of invalidating the token (in secretOrKeyProvider). Thank you for the general explanation. The staleless token argument forces me to think about it some more. Good point.

          – Tom Siwik
          Mar 27 at 8:17






          This is precisely what I ended up doing (no other choise with nestjs/jwt). Except that I store the token in the user itself instead of decoding the token for the purpose of invalidating the token (in secretOrKeyProvider). Thank you for the general explanation. The staleless token argument forces me to think about it some more. Good point.

          – Tom Siwik
          Mar 27 at 8:17





          1




          1





          Glad to hear. :) If it's not a hard requirement consider rotating the keys frequently instead by making use of jwt's kid property

          – Kim Kern
          Mar 27 at 8:26





          Glad to hear. :) If it's not a hard requirement consider rotating the keys frequently instead by making use of jwt's kid property

          – Kim Kern
          Mar 27 at 8:26













          This is a very good idea. Do you have any sources how this is used in practice I can look up? I assume this needs to be done with a secretOrKeyProvider to temporarily accept previously used secrets?

          – Tom Siwik
          Mar 27 at 9:45





          This is a very good idea. Do you have any sources how this is used in practice I can look up? I assume this needs to be done with a secretOrKeyProvider to temporarily accept previously used secrets?

          – Tom Siwik
          Mar 27 at 9:45













          Yep, at least for the expiration time you have to accept old keys. I haven't implemented it myself so I can't really point to a good ressource, sorry

          – Kim Kern
          Mar 27 at 11:00






          Yep, at least for the expiration time you have to accept old keys. I haven't implemented it myself so I can't really point to a good ressource, sorry

          – Kim Kern
          Mar 27 at 11:00














          Thanks, no problem. This small hint might be enough already. I'll try to come up with an elegant solution. Cheers

          – Tom Siwik
          Mar 27 at 11:24





          Thanks, no problem. This small hint might be enough already. I'll try to come up with an elegant solution. Cheers

          – Tom Siwik
          Mar 27 at 11:24








          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55354102%2fusing-nestjs-jwt-signing-with-dynamic-user-related-secret%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript