jwt / ruby-jwt

A ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.
http://ruby-jwt.org
MIT License
3.6k stars 377 forks source link

Verify tokens without throwing exceptions #124

Open kwando opened 8 years ago

kwando commented 8 years ago

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

excpt commented 8 years ago

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
kwando commented 8 years ago

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
fabioxgn commented 8 years ago

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

excpt commented 8 years ago

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

kwando commented 8 years ago

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.

excpt commented 8 years ago

@kwando Looking forward seeing your ideas.

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

JoeWoodward commented 6 years ago

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

excpt commented 6 years ago

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

ab320012 commented 6 years ago

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

Tonyynot14 commented 5 years ago

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