• Stars
    star
    205
  • Rank 191,264 (Top 4 %)
  • Language
    Crystal
  • License
    MIT License
  • Created almost 9 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JWT implementation in Crystal

Crystal JWT

CI

An implementation of JSON Web Token (JWT) in Crystal programming language.

Installation

Add this to your application's shard.yml:

dependencies:
  jwt:
    github: crystal-community/jwt

Usage

# Encoding
payload = { "foo" => "bar" }
token = JWT.encode(payload, "SecretKey", JWT::Algorithm::HS256)
# => "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmb28iOiJiYXIifQ.Y3shN5Wh4FmOPM34biIm9QQmat373hJFKNxgSANQWJo"

# Custom headers
token = JWT.encode(payload, "SecretKey", JWT::Algorithm::HS256, custom: "header")

# Decoding
payload, header = JWT.decode(token, "$secretKey", JWT::Algorithm::HS256)
# payload = {"foo" => "bar"}
# header = {"typ" => "JWT", "alg" => "HS256"}

# You can optionally ignore verification and validation if you want to inspect the token
payload, header = JWT.decode(token, verify: false, validate: false)
# Verification checks the signature
# Validation is checking if the token has expired etc

# You may dynamically decide the key by passing a block to the decode function
# the algorithm is optional, you can omit it to use algorithm defined in the header
payload, header = JWT.decode(token, JWT::Algorithm::HS256) do |header, payload|
  "the key"
end

Supported algorithms

  • none
  • HMAC (HS256, HS384, HS512)
  • RSA (RS256, RS384, RS512)
  • ECDSA (ES256, ES384, ES512)

Supported reserved claim names

JSON Web Token defines some reserved claim names and how they should be used.

Expiration Time (exp)

From RFC 7519:

The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the "exp" claim requires that the current date/time MUST be before the expiration date/time listed in the "exp" claim. Implementers MAY provide for some small leeway, 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

Example:

# Create token that expires in 1 minute
exp = Time.utc.to_unix + 60
payload = { "foo" => "bar", "exp" => exp }
token = JWT.encode(payload, "SecretKey", JWT::Algorithm::HS256)

# At this moment token can be decoded
payload, header = JWT.decode(token, "SecretKey", JWT::Algorithm::HS256)

sleep 61
# Now token is expired, so JWT::ExpiredSignatureError will be raised
payload, header = JWT.decode(token, "SecretKey", JWT::Algorithm::HS256)

Not Before Time (nbf)

From RFC 7519:

MUST NOT be accepted for processing. The processing of the "nbf" The "nbf" (not before) claim identifies the time before which the JWT claim requires that the current date/time MUST be after or equal to the not-before date/time listed in the "nbf" claim. Implementers MAY provide for some small leeway, 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.

Example:

# Create token that will become acceptable in 1 minute
nbf = Time.utc.to_unix + 60
payload = { "foo" => "bar", "nbf" => nbf }
token = JWT.encode(payload, "SecretKey", JWT::Algorithm::HS256)

# Currently it's not acceptable, raises JWT::ImmatureSignatureError
JWT.decode(token, "SecretKey", JWT::Algorithm::HS256)

Issued At (iat)

From RFC 7519:

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.

Example:

payload = { "foo" => "bar", "iat" => Time.utc.to_unix }
token = JWT.encode(payload, "SecretKey", JWT::Algorithm::HS256)

Audience (aud)

From RFC 7519:

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 the aud claim when this claim is present, then the JWT MUST be rejected. In the general case, the aud value is an array of case-sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the aud value 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.

Example:

payload = {"foo" => "bar", "aud" => ["sergey", "julia"]}
token = JWT.encode(payload, "key", JWT::Algorithm::HS256)

# OK, aud matches
payload, header = JWT.decode(token, "key", JWT::Algorithm::HS256, aud: "sergey")

# aud does not match, raises JWT::InvalidAudienceError
payload, header = JWT.decode(token, "key", JWT::Algorithm::HS256, aud: "max")

Issuer (iss)

From RFC 7519:

The iss (issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. The iss value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL.

Example:

payload = { "foo" => "bar", "iss" => "me"}
token = JWT.encode(payload, "SecretKey", "HS256")

# OK, because iss matches
payload, header = JWT.decode(token, "SecretKey", JWT::Algorithm::HS256, iss: "me")

# iss does not match, raises JWT::InvalidIssuerError
payload, header = JWT.decode(token, "SecretKey", JWT::Algorithm::HS256, iss: "you")

Subject (sub)

From RFC 7519:

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.

Example:

payload = { "nomo" => "Sergeo", "sub" => "Esperanto" }
token = JWT.encode(payload, "key", JWT::Algorithm::HS256)

# Raises JWT::InvalidSubjectError, because "sub" claim does not match
JWT.decode(token, "key", JWT::Algorithm::HS256, sub: "Junularo")

JWT ID (jti)

From RFC 7519:

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. The jti claim can be used to prevent the JWT from being replayed. The jti value is a case-sensitive string. Use of this claim is OPTIONAL.

Example:

require "secure_random"

jti = SecureRandom.urlsafe_base64
payload = { "foo" => "bar", "jti" => jti }
token = JWT.encode(payload, "SecretKey", JWT::Algorithm::HS256)

Exceptions

  • JWT::Error
    • JWT::DecodeError
      • JWT::VerificationError
      • JWT::ExpiredSignatureError
      • JWT::ImmatureSignatureError
      • JWT::InvalidAudienceError
      • JWT::InvalidIssuerError
      • JWT::InvalidSubjectError
    • UnsupportedAlgorithmError

Test

crystal spec

Contributors

  • greyblake Potapov Sergey - creator, maintainer

More Repositories

1

icr

Interactive console for Crystal programming language
Crystal
502
star
2

crystal-patterns

πŸ“– Examples of GOF patterns written in Crystal
Crystal
294
star
3

crystal-libraries-needed

A list of libraries that are needed or wanted for the Crystal-Language
141
star
4

msgpack-crystal

MessagePack implementation in Crystal msgpack.org[Crystal]
Crystal
136
star
5

cossack

Simple and flexible HTTP client for Crystal with middleware and test support.
Crystal
106
star
6

hardware

Get CPU, Memory and Network informations of the running OS and its processes
Crystal
72
star
7

kiwi

A unified Crystal interface for key-value stores.
Crystal
64
star
8

toml.cr

TOML parser for Crystal
Crystal
60
star
9

zeromq-crystal

Crystal
48
star
10

crystal-ann

Web site to announce new Crystal projects, blog posts, updates and other work activities
CSS
45
star
11

leveldb

Crystal binding for LevelDB
Crystal
39
star
12

future.cr

Crystal
34
star
13

bloom_filter

Bloom filter implementation in Crystal lang
Crystal
34
star
14

timecop.cr

A testing library that allows "time travel," "freezing time," and "time acceleration". Inspired by the ruby-timecop library.
Crystal
19
star
15

crystal-kcov

Crystal
17
star
16

autolink.cr

πŸ”— Auto link for Crystal
Crystal
16
star
17

crystal-notifications

A library for notifications, this started as a port from ActiveSupport::Notifications
Crystal
16
star
18

bluetooth

Bluetooth Bluez binding in Crystal
Crystal
10
star
19

cr-config

An all-in-one configuration library to handle any possible configuration need
Crystal
10
star
20

community

The crystal community
10
star
21

snappy-crystal

Snappy bindings for Crystal
Crystal
6
star
22

cr-i18n

Crystal
3
star
23

kilt-components

Crystal
2
star