exsimpleauth v0.2.0 ExSimpleAuth.Token

Genrate and verify token

Link to this section Summary

Functions

Generate JWT token with supplied data

Check the supplied token and it’s expiration

Link to this section Functions

Link to this function generate(data, opts \\ [])

Generate JWT token with supplied data

Options

  • :key - decryption key. If not used, then read SECRET_KEY variable from system environment.
  • :expiration - epiration time in seconds. Should be nonnegative integer. Default is 86400 seconds and it is 24 hours.
  • :iat - issued at. Unix timestamp. Default DateTime.utc_now() |> DateTime.to_unix().

Returns JWT token as binary (t:String.t).

Examples

iex> key = "y):'QGE8M-b+MEKl@k4e<;*9.BqL=@~B"
...> data = %{"foo": 1234}
...> ExSimpleAuth.Token.generate(data, key: key, iat: 1516788472)
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MTY3ODg0NzIsImV4cCI6MTUxNjg3NDg3MiwiZGF0YSI6eyJmb28iOjEyMzR9fQ.vTHve65J0r48eTQdABKVzVMWj1E1IQCKTKM-OInh2Hk"
Link to this function verify(token, opts \\ [])

Check the supplied token and it’s expiration.

Options

  • :key - decryption key. If not used, then read SECRET_KEY variable from system environment.

Returns

  • {:ok, data} - token is valid.
  • {:error, "invalid JWT"} - invalid token
  • {:error, [:exp,...]} - invalid claim (eg. token expired)

Examples

returns data if token is valid

iex> key = "y):'QGE8M-b+MEKl@k4e<;*9.BqL=@~B"
...> data = %{"foo": 1234}
...> token = ExSimpleAuth.Token.generate(data, key: key)
...> ExSimpleAuth.Token.verify(token, key: key)
{:ok, %{"foo": 1234}}

returns expiration error when token expire

iex> key = "y):'QGE8M-b+MEKl@k4e<;*9.BqL=@~B"
...> data = %{"foo": 1234}
...> token = ExSimpleAuth.Token.generate(data, key: key, expiration: 0)
...> ExSimpleAuth.Token.verify(token, key: key)
{:error, [:exp]}

returns error if token is invalid

iex> key = "y):'QGE8M-b+MEKl@k4e<;*9.BqL=@~B"
...> data = %{"foo": 1234}
...> token = ExSimpleAuth.Token.generate(data, key: key)
...> key2 = "12345678901234567890123456789012"
...> ExSimpleAuth.Token.verify(token, key: key2)
{:error, "invalid JWT"}