Error invalid expiresin option for string payload

I am trying to set the expiresIn function in my javascript app. I am following the documentation, but I keep getting this error. Can anyone see what I am doing wrong? app.get("/user", asy...

I am trying to set the expiresIn function in my javascript app. I am following the documentation, but I keep getting this error. Can anyone see what I am doing wrong?

app.get("/user", async (req, res) => {
  const { name } = req.body;
  const accessToken = jsonwebtoken.sign( name, process.env.ACCESS_TOKEN_SECRET, { expiresIn: 60 * 60});
  res.json({ accessToken: accessToken, name })
  console.log(accessToken, name)
})

asked Mar 3, 2021 at 2:28

Howie's user avatar

Your payload needs to be an object otherwise it’s treated as a string. Try this

const accessToken = jsonwebtoken.sign( {name: name}, process.env.ACCESS_TOKEN_SECRET, { expiresIn: 60 * 60});

answered Mar 3, 2021 at 2:43

Rifat Bin Reza's user avatar

Rifat Bin RezaRifat Bin Reza

2,4092 gold badges13 silver badges29 bronze badges

➜  backend git:(user-auth) ✗ node
> var j= require('jsonwebtoken');
undefined
> j.sign('test', 'test', {expiresInMinutes:1});
invalid "expiresInMinutes" option for string payload
jsonwebtoken: expiresInMinutes and expiresInSeconds is deprecated. ()
Use "expiresIn" expressed in seconds.
'eyJhbGciOiJIUzI1NiJ9.dGVzdA.2WmFS_EAdYFCBOFM9pVPo9g4bpuI2I9U_JGTCfrx7Tk'
> j.sign('test', 'test', {expiresIn:60});
invalid "expiresIn" option for string payload
Error: "expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60
    at Object.JWT.sign (/Users/joehenry/meals/backend/node_modules/jsonwebtoken/index.js:109:13)
    at repl:1:3
    at REPLServer.defaultEval (repl.js:252:27)
    at bound (domain.js:287:14)
    at REPLServer.runBound [as eval] (domain.js:300:12)
    at REPLServer.<anonymous> (repl.js:417:12)
    at emitOne (events.js:82:20)
    at REPLServer.emit (events.js:169:7)
    at REPLServer.Interface._onLine (readline.js:210:10)
    at REPLServer.Interface._line (readline.js:549:8)
> 

Am I doing something wrong?

expiresInMinutes was deprecated, you should use expiresIn: '5m' for instance.

Where did you saw that so we can update?

I was getting a deprecation for expiresInMinutes so changed to expireIn, and am still getting similar.
var token = jwt.sign(escaped, config.secret, { expiresIn: '5h' });
and
var token = jwt.sign(escaped, config.secret, { expiresIn: 60*60*5 });
both resulted in the error

invalid "expiresIn" option for string payload
Error: "expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60

It looks like the issue is exactly what the warning is. You can’t put an expiration on a string payload. It throws a warning about it then continues to fall through and attempt to set payload.exp (but payload is a string), then sees that payload.exp is undefined so assumed you passed something poorly instead of ignoring the invalid option.

yes, I am planning to fail that explicitly instead of warning on the next major version

@rjVapes, ah, I see. If I pass in an object it works. Only for strings does the exp not work. Thanks for pointing that out.

So instead of using this in my code:

return done(err, status, jwt.sign(JSON.stringify(jsonToken), config.secret, {expiresIn: '10h'}));

I instead have to use this?

return done(err, status, jwt.sign(jsonToken, config.secret, {expiresIn: '10h'}));

Is that what we’re looking at here? This has been driving me crazy because no matter what I did with the expires time, it failed. And it didn’t fail on all environments where the application was running.

@michaeloryl yes, if you use an string payload expiresIn is ignored. You should use an object instead.

Thanks @michaeloryl I think the error message should be more explicit… I lost a couple of hours here also

@jfromaniello jfromaniello
Just out of curiosity… why is expiresIn ignored when I pass a string instead of an object? What’s the reason for such an implementation?

@kamilbrzezinski JWT is JSON Web Token, the exp field is an standard claim and is part of the json.

an string is a valid json:

> JSON.stringify("foo")
'"foo"'
> JSON.parse(JSON.stringify("foo")) === 'foo'
true

but a string can’t have a property… it will be the equivalent to something like this:

> var a = "foo"
> a.exp = 12333
> JSON.stringify(a)
'"foo"'

Besides the fact that you can’t add a property to an string in javascript, there is not a representation in JSON of an string with a property.

if I set the expiry as { expiresIn : ‘365d’ } , so should i be assured it will last for 1 year

I’m sorry but i didnt understand nothing…. i’m using JSON.stringify(‘7d’) and it’s not working at all… and the error is caming from the verify :
«Illegal argument undefined»

I have no words

@Masterchoc can you explain what you are trying to do? Thanks

for me ,this error occurs because payload is string.
pass object like this to sign function
let payload ={test: 'test string'}

I was getting this error, and it had nothing to do with the options I was passing or anything to do with the expiresIn option. Like what @alikarimii was saying, the payload you are signing needs to be an Object.
WRONG: jwt.sign(user.id, secret, { expiresIn: 60 * 60, algorithm: 'HS256'})
GOOD: jwt.sign({ uid: user.id }, secret, { expiresIn: 60 * 60, algorithm: 'HS256'})

@ddcech , good info, thanks it’s work , the solution is to put an object

I was using JSON.stringify() then it breaks the options.

jwt.sign(JSON.stringify(profile},process.env.SECRET,{expiresIn: 60 * 60, algorithm: "HS256"})

When I use JSON.stringify, even options are OK as @ddcech described good ones, it breaks. So I change it to.

jwt.sign({profile},process.env.SECRET,{expiresIn: 60 * 60, algorithm: "HS256"})

Thank you ddcech! This work —
jwt.sign( { userId: user.id }, config.secret , { expiresIn: "2h" });

So instead of using this in my code:

return done(err, status, jwt.sign(JSON.stringify(jsonToken), config.secret, {expiresIn: '10h'}));

I instead have to use this?

return done(err, status, jwt.sign(jsonToken, config.secret, {expiresIn: '10h'}));

Is that what we’re looking at here? This has been driving me crazy because no matter what I did with the expires time, it failed. And it didn’t fail on all environments where the application was running.

That helped me a lot ty

a019 Asks: Complex equations: NDSolveValue / FEM,
So, I am trying to solve a simple problem using the FEM method.

The distribution of Voltage over a region,

The region is,

Code:

  << NDSolve`FEM`
bm = ToBoundaryMesh[
   "Coordinates" -> {{0., 0.}, {1., 0.}, {12/10, 0.}, {12/10, 1.}, {1., 
      1.}, {0., 1.}}, 
   "BoundaryElements" -> {LineElement[{{1, 2}, {2, 3}, {3, 4}, {4, 
        5}, {5, 6}, {6, 1}, {5, 2}}]}];
em = ToElementMesh[bm, 
   "RegionMarker" -> {{{0.5, 0.5}, 1}, {{1.2, 0.5}, 2}}];

which look like this,

Code:

     Show[{
  em["Wireframe"["MeshElementStyle" -> Directive[EdgeForm[Red], Thin],
     "MeshElementMarkerStyle" -> Blue]],
  bm["Wireframe"["MeshElementStyle" -> Black]]
  }, ImageSize -> 300]

enter image description here

I have two equations,

Code:

op1 = Laplacian[v1[x, y], {x, y}];
op2= Laplacian[v2[x, y], {x, y}];

bc1=DirichletCondition[v1[x, y] == 4, x == 12/10];
bc2=DirichletCondition[v2[x, y] == 0, x == 0];

omg=376.991;
dd=100;
d=25*10^-6;

 eef={4.18382,4.22462,9.95342,12.8216,13.9473,14.4967,14.8028,14.9896,15.1113,15.195,15.2551,15.2998,15.3341,15.3611,15.3829,15.4007,15.4155,15.428,15.4387,15.4478,15.4556,15.4624,15.4682,15.4733,15.4777};
    ee1 = ListInterpolation[eef, InterpolationOrder -> 1]

ee1 has dependence on v1[x,y]-v2[x,y], as ee1[Abs[v1[x,y]-v2[x,y]]]

Code:

{v1fun,v2fun} = NDSolveValue[{op1==If[ElementMarker == 1, ((I omg ee1[
     Abs[v1[x, y] - v2[x, y]]])/(dd d)) (v1[x, y] - 
     v2[x, y]), 0], op2==If[ElementMarker == 1, (
   (I omg ee1[
     Abs[v1[x, y] - v2[x, y]]])/(dd d)) (v2[x, y] - 
     v1[x, y]), 0],bc1,bc2},{v1[x, y],v2{x,y}}, {x, y} ∈ em]

The output contour plot of (Abs[v1[x,y]-v2[x,y]]) should be the distribution of voltage over the entire mesh region with the highest values at the x=0 and x=1.2.

I am getting different errors in versions 11.1 and 13.1. I am trying to solve complex equations in NdSolveValue and FEM.

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others.

Getting the error

"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60

I looked at where the error was being thrown in index.js line 86:

payload.exp = timespan(options.expiresIn);

I stepped through the timespan function and everything looks good there if I pass in either string or number. However the function always returns undefined?

All 5 comments

I should have read the documentation better:

payload could be an object literal, buffer or string. Please note that exp is only set if the payload is an object literal.

I was sending in a string.

Closing as non-issue.

After updating to 5.5, I started seeing this error, whereas I wasn’t seeing it before.

I am also passing a string in rather than an object literal, so I went ahead and removed the expiration since it’s not being used and it cleared the error up.

However, this error message is incorrect — the format of «expiresIn» was correct, so this is an open bug in my opinion.

Notice that it will be silently ignored now when the payload doesn’t support expiration. I plan to fail explicitly in the next major version.

Out of nowhere I’m facing exact same issue. First it was working fine and now its giving me this error
invalid expiresIn option for string payload

const accessToken = jwt.sign(phone, JWT_AUTH_TOKEN, { expiresIn: '30s' });
const refreshToken = jwt.sign(phone, JWT_REFRESH_TOKEN, { expiresIn: '1y' });

Was this page helpful?

0 / 5 — 0 ratings

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.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • 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.

  • Visualization

    Some thing interesting about visualization, use data art

  • 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.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

@salali

Getting the error

"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60

I looked at where the error was being thrown in index.js line 86:

payload.exp = timespan(options.expiresIn);

I stepped through the timespan function and everything looks good there if I pass in either string or number. However the function always returns undefined?

@salali

I should have read the documentation better:

payload could be an object literal, buffer or string. Please note that exp is only set if the payload is an object literal.

I was sending in a string.

Closing as non-issue.

@jgentes

After updating to 5.5, I started seeing this error, whereas I wasn’t seeing it before.

I am also passing a string in rather than an object literal, so I went ahead and removed the expiration since it’s not being used and it cleared the error up.

However, this error message is incorrect — the format of «expiresIn» was correct, so this is an open bug in my opinion.

@jgentes

@jfromaniello

Notice that it will be silently ignored now when the payload doesn’t support expiration. I plan to fail explicitly in the next major version.

@MeRahulAhire

Out of nowhere I’m facing exact same issue. First it was working fine and now its giving me this error
invalid expiresIn option for string payload

const accessToken = jwt.sign(phone, JWT_AUTH_TOKEN, { expiresIn: '30s' });
const refreshToken = jwt.sign(phone, JWT_REFRESH_TOKEN, { expiresIn: '1y' });

@skibaalex

@MeRahulAhire

@nayabahmad

@gautam2002

@xinthose

Just make the payload an object:
Wrong: sign(data.username, ...
Right: sign({ "username": data.username }, ...

@kirilritobis

Just make the payload an object: Wrong: sign(data.username, ... Right: sign({ "username": data.username }, ...

That solved the problem. Thank you

@juannguyenicd

Понравилась статья? Поделить с друзьями:
  • Error invalid environment block
  • Error invalid email
  • Error invalid download state try resuming
  • Error invalid digit 8 in octal constant
  • Error invalid data directory postgresql