ruby-jwt icon indicating copy to clipboard operation
ruby-jwt copied to clipboard

Verify tokens without throwing exceptions

Open kwando opened this issue 10 years ago • 10 comments

It would be very nice to be able to verify a token without having to rescue exceptions..

kwando avatar Jan 18 '16 08:01 kwando

Hi @kwando,

do you mean something like this?

Pseudocode:

exp = Time.now.to_i + 4 * 3600
exp_payload = { :data => 'data', :exp => exp }

token = JWT.encode exp_payload, hmac_secret, 'HS256'

decoded_token = JWT.decode token, hmac_secret, true, { :algorithm => 'HS256' }

if JWT.has_error?
  puts JWT.get_errors # returns array of errors ['Exp is invalid', 'Algo does not match.']
end

excpt avatar Jan 18 '16 09:01 excpt

Not with global state like that.

exp = Time.now.to_i + 4 * 3600
exp_payload = { :data => 'data', :exp => exp }

token = JWT.encode(exp_payload, hmac_secret, 'HS256')

result = JWT.decode(token, hmac_secret, true, { :algorithm => 'HS256' })

if result.errors?
  puts result.errors # returns array of errors ['Exp is invalid', 'Algo does not match.']
end

result.value # returns the decoded claims

kwando avatar Jan 18 '16 09:01 kwando

@kwando @excpt agreed. It is never nice to use exception for flow control: http://programmers.stackexchange.com/a/189225

The main problem of doing this would be backwards compatibility.

fabioxgn avatar Feb 07 '16 08:02 fabioxgn

@fabioxgn If we're planning this one correct we introduce simply an API change / break with version 2.0. This shouldn't be a problem.

excpt avatar Feb 08 '16 17:02 excpt

I'm willing to invest some time into this endeavor. I think the verification API needs an overhaul too and it would be a good to look into that if we are doing a 2.0.

kwando avatar Feb 09 '16 10:02 kwando

@kwando Looking forward seeing your ideas.

You may have a look at #110 for a more advanced discussion into the 2.0 verification API.

excpt avatar Feb 09 '16 10:02 excpt

what ever happened to this. It seems like flow control is still managed through exceptions. Am I missing something?

JoeWoodward avatar Feb 21 '18 08:02 JoeWoodward

This proposed change didn’t make it into 2.0. This is still an open issue.

excpt avatar Feb 25 '18 09:02 excpt

@excpt @JoeWoodward i think it would make sense to introduce a new class like DecodedToken with the interface #errors and #value. We can initialize the class at the beginning of JWT#decode method and return at the end.

ab320012 avatar Apr 23 '18 12:04 ab320012

How can these exceptions be rescued? It just throws a 500 server error when they occur.

Tonyynot14 avatar Jul 05 '19 15:07 Tonyynot14