The purpose of this fork is to restore Ruby 1.8.7 compatibility to this gem. { :hash_rockets => '4 lyfe' }
A pure ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.
If you have further questions releated to development or usage, join us: ruby-jwt google group.
sudo gem install jwtThe JWT spec supports NONE, HMAC, RSASSA, ECDSA and RSASSA-PSS algorithms for cryptographic signing. Currently the jwt gem supports NONE, HMAC, RSASSA and ECDSA. If you are using cryptographic signing, you need to specify the algorithm in the options hash whenever you call JWT.decode to ensure that an attacker cannot bypass the algorithm verification step.
See: JSON Web Algorithms (JWA) 3.1. "alg" (Algorithm) Header Parameter Values for JWS
NONE
- none - unsigned token
require'jwt'payload={:data=>'test'}# IMPORTANT: set nil as password parametertoken=JWT.encodepayload,nil,'none'# eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJ0ZXN0IjoiZGF0YSJ9.putstoken# Set password to nil and validation to false otherwise this won't workdecoded_token=JWT.decodetoken,nil,false# Array# [# {"data"=>"test"}, # payload# {"typ"=>"JWT", "alg"=>"none"} # header# ]putsdecoded_tokenHMAC (default: HS256)
- HS256 - HMAC using SHA-256 hash algorithm (default)
- HS384 - HMAC using SHA-384 hash algorithm
- HS512 - HMAC using SHA-512 hash algorithm
hmac_secret='my$ecretK3y'token=JWT.encodepayload,hmac_secret,'HS256'# eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0ZXN0IjoiZGF0YSJ9._sLPAGP-IXgho8BkMGQ86N2mah7vDyn0L5hOR4UkfoIputstokendecoded_token=JWT.decodetoken,hmac_secret,true,{:algorithm=>'HS256'}# Array# [# {"data"=>"test"}, # payload# {"typ"=>"JWT", "alg"=>"HS256"} # header# ]putsdecoded_tokenRSA
- RS256 - RSA using SHA-256 hash algorithm
- RS384 - RSA using SHA-384 hash algorithm
- RS512 - RSA using SHA-512 hash algorithm
rsa_private=OpenSSL::PKey::RSA.generate2048rsa_public=rsa_private.public_keytoken=JWT.encodepayload,rsa_private,'RS256'# eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ0ZXN0IjoiZGF0YSJ9.c2FynXNyi6_PeKxrDGxfS3OLwQ8lTDbWBWdq7oMviCy2ZfFpzvW2E_odCWJrbLof-eplHCsKzW7MGAntHMALXgclm_Cs9i2Exi6BZHzpr9suYkrhIjwqV1tCgMBCQpdeMwIq6SyKVjgH3L51ivIt0-GDDPDH1Rcut3jRQzp3Q35bg3tcI2iVg7t3Msvl9QrxXAdYNFiS5KXH22aJZ8X_O2HgqVYBXfSB1ygTYUmKTIIyLbntPQ7R22rFko1knGWOgQCoYXwbtpuKRZVFrxX958L2gUWgb4jEQNf3fhOtkBm1mJpj-7BGst00o8g_3P2zHy-3aKgpPo1XlKQGjRrrxAputstokendecoded_token=JWT.decodetoken,rsa_public,true,{:algorithm=>'RS256'}# Array# [# {"data"=>"test"}, # payload# {"typ"=>"JWT", "alg"=>"RS256"} # header# ]putsdecoded_tokenECDSA
- ES256 - ECDSA using P-256 and SHA-256
- ES384 - ECDSA using P-384 and SHA-384
- ES512 - ECDSA using P-521 and SHA-512
ecdsa_key=OpenSSL::PKey::EC.new'prime256v1'ecdsa_key.generate_keyecdsa_public=OpenSSL::PKey::EC.newecdsa_keyecdsa_public.private_key=niltoken=JWT.encodepayload,ecdsa_key,'ES256'# eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJ0ZXN0IjoiZGF0YSJ9.MEQCIAtShrxRwP1L9SapqaT4f7hajDJH4t_rfm-YlZcNDsBNAiB64M4-JRfyS8nRMlywtQ9lHbvvec9U54KznzOe1YxTyAputstokendecoded_token=JWT.decodetoken,ecdsa_public,true,{:algorithm=>'ES256'}# Array# [# {"test"=>"data"}, # payload# {"typ"=>"JWT", "alg"=>"ES256"} # header# ]putsdecoded_tokenRSASSA-PSS
Not implemented.
JSON Web Token defines some reserved claim names and defines how they should be used. JWT supports these reserved claim names:
- 'exp' (Expiration Time) Claim
- 'nbf' (Not Before Time) Claim
- 'iss' (Issuer) Claim
- 'aud' (Audience) Claim
- 'jti' (JWT ID) Claim
- 'iat' (Issued At) Claim
- 'sub' (Subject) Claim
From Oauth JSON Web Token 4.1.4. "exp" (Expiration Time) Claim:
The
exp(expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of theexpclaim requires that the current date/time MUST be before the expiration date/time listed in theexpclaim. Implementers MAY provide for some smallleeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.
Handle Expiration Claim
exp=Time.now.to_i + 4 * 3600exp_payload={:data=>'data',:exp=>exp}token=JWT.encodeexp_payload,hmac_secret,'HS256'begindecoded_token=JWT.decodetoken,hmac_secret,true,{:algorithm=>'HS256'}rescueJWT::ExpiredSignature# Handle expired token, e.g. logout user or deny accessendAdding Leeway
exp=Time.now.to_i - 10leeway=30# secondsexp_payload={:data=>'data',:exp=>exp}# build expired tokentoken=JWT.encodeexp_payload,hmac_secret,'HS256'begin# add leeway to ensure the token is still accepteddecoded_token=JWT.decodetoken,hmac_secret,true,{:leeway=>leeway,:algorithm=>'HS256'}rescueJWT::ExpiredSignature# Handle expired token, e.g. logout user or deny accessendFrom Oauth JSON Web Token 4.1.5. "nbf" (Not Before) Claim:
The
nbf(not before) claim identifies the time before which the JWT MUST NOT be accepted for processing. The processing of thenbfclaim requires that the current date/time MUST be after or equal to the not-before date/time listed in thenbfclaim. Implementers MAY provide for some smallleeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.
Handle Not Before Claim
nbf=Time.now.to_i - 3600nbf_payload={:data=>'data',:nbf=>nbf}token=JWT.encodenbf_payload,hmac_secret,'HS256'begindecoded_token=JWT.decodetoken,hmac_secret,true,{:algorithm=>'HS256'}rescueJWT::ImmatureSignature# Handle invalid token, e.g. logout user or deny accessendAdding Leeway
nbf=Time.now.to_i + 10leeway=30nbf_payload={:data=>'data',:nbf=>nbf}# build expired tokentoken=JWT.encodenbf_payload,hmac_secret,'HS256'begin# add leeway to ensure the token is validdecoded_token=JWT.decodetoken,hmac_secret,true,{:leeway=>leeway,:algorithm=>'HS256'}rescueJWT::ImmatureSignature# Handle invalid token, e.g. logout user or deny accessendFrom Oauth JSON Web Token 4.1.1. "iss" (Issuer) Claim:
The
iss(issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. Theissvalue is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL.
iss='My Awesome Company Inc. or https://my.awesome.website/'iss_payload={:data=>'data',:iss=>iss}token=JWT.encodeiss_payload,hmac_secret,'HS256'begin# Add iss to the validation to check if the token has been manipulateddecoded_token=JWT.decodetoken,hmac_secret,true,{:iss=>iss,:verify_iss=>true,:algorithm=>'HS256'}rescueJWT::InvalidIssuerError# Handle invalid token, e.g. logout user or deny accessendFrom Oauth JSON Web Token 4.1.3. "aud" (Audience) Claim:
The
aud(audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in theaudclaim when this claim is present, then the JWT MUST be rejected. In the general case, theaudvalue is an array of case-sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, theaudvalue MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL.
aud=['Young','Old']aud_payload={:data=>'data',:aud=>aud}token=JWT.encodeaud_payload,hmac_secret,'HS256'begin# Add aud to the validation to check if the token has been manipulateddecoded_token=JWT.decodetoken,hmac_secret,true,{:aud=>aud,:verify_aud=>true,:algorithm=>'HS256'}rescueJWT::InvalidAudError# Handle invalid token, e.g. logout user or deny accessputs'Audience Error'endFrom Oauth JSON Web Token 4.1.7. "jti" (JWT ID) Claim:
The
jti(JWT ID) claim provides a unique identifier for the JWT. The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well. Thejticlaim can be used to prevent the JWT from being replayed. Thejtivalue is a case-sensitive string. Use of this claim is OPTIONAL.
# in order to use JTI you have to add iatiat=Time.now.to_i# Use the secret and iat to create a unique key per request to prevent replay attacksjti_raw=[hmac_secret,iat].join(':').to_sjti=Digest::MD5.hexdigest(jti_raw)jti_payload={:data=>'data',:iat=>iat,:jti=>jti}token=JWT.encodejti_payload,hmac_secret,'HS256'begin# Add jti and iat to the validation to check if the token has been manipulateddecoded_token=JWT.decodetoken,hmac_secret,true,{'jti'=>jti,:verify_jti=>true,:algorithm=>'HS256'}# Check if the JTI has already been usedrescueJWT::InvalidJtiError# Handle invalid token, e.g. logout user or deny accessputs'Error'endFrom Oauth JSON Web Token 4.1.6. "iat" (Issued At) Claim:
The
iat(issued at) claim identifies the time at which the JWT was issued. This claim can be used to determine the age of the JWT. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.
iat=Time.now.to_iiat_payload={:data=>'data',:iat=>iat}token=JWT.encodeiat_payload,hmac_secret,'HS256'begin# Add iat to the validation to check if the token has been manipulateddecoded_token=JWT.decodetoken,hmac_secret,true,{:verify_iat=>true,:algorithm=>'HS256'}rescueJWT::InvalidIatError# Handle invalid token, e.g. logout user or deny accessendFrom Oauth JSON Web Token 4.1.2. "sub" (Subject) Claim:
The
sub(subject) claim identifies the principal that is the subject of the JWT. The Claims in a JWT are normally statements about the subject. The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique. The processing of this claim is generally application specific. The sub value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL.
sub='Subject'sub_payload={:data=>'data',:sub=>sub}token=JWT.encodesub_payload,hmac_secret,'HS256'begin# Add sub to the validation to check if the token has been manipulateddecoded_token=JWT.decodetoken,hmac_secret,true,{'sub'=>sub,:verify_sub=>true,:algorithm=>'HS256'}rescueJWT::InvalidSubError# Handle invalid token, e.g. logout user or deny accessendWe depend on Echoe for defining gemspec and performing releases to rubygems.org, which can be done with
rake releaseThe tests are written with rspec. Given you have rake and rspec, you can run tests with
rake testIf you want a release cut with your PR, please include a version bump according to Semantic Versioning
- Jordan Brough github.jordanb@xoxy.net
- Ilya Zhitomirskiy ilya@joindiaspora.com
- Daniel Grippi daniel@joindiaspora.com
- Jeff Lindsay progrium@gmail.com
- Bob Aman bob@sporkmonger.com
- Micah Gates github@mgates.com
- Rob Wygand rob@wygand.com
- Ariel Salomon (Oscil8)
- Paul Battley pbattley@gmail.com
- Zane Shannon @zshannon
- Brian Fletcher @punkle
- Alex @ZhangHanDong
- John Downey @jtdowney
- Adam Greene @skippy
- Tim Rudat @excpttimrudat@gmail.com - Maintainer
MIT
Copyright (c) 2011 Jeff Lindsay
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.