simonh1000/elm-jwt/2.0.0

NOTE: this package is not compatible with Elm 0.19.1

Jwt

Helper functions for Jwt token authentication.

A Jwt Token comprises 3 elements: a header and footer and the content. This package includes a function to send an authentication request, a function to read the content of a token; and a function to send GET requests with the token attached.

API functions

authenticate : Decoder String -> String -> String -> Task JwtError String

authenticate is a custom Http POST method that sends a stringified Json object containing the login credentials. It then extracts the token from the json response from the server and returns it.

let credentials =
    E.object
        [ ("username", E.string model.uname)
        , ("password", E.string model.pword)
        ]
    |> E.encode 0
in
( model
, Task.perform
    LoginFail LoginSuccess
    (authenticate tokenStringDecoder "/sessions" credentials)
)
decodeToken : Decoder a -> String -> Result JwtError a

decodeToken converts the token content to an Elm record structure.

decoderToken dec token

In the event of success, decodeToken returns an Elm record structure using the JSON Decoder.

send : String -> Token -> Decoder a -> String -> Body -> Task Error a

send is a replacement for Http.send that includes a Jwt token

get : Token -> Decoder a -> String -> Task Error a

get is a replacement for Http.get that attaches a provided Jwt token to the headers of the GET request.

Task.perform
    PostFail PostSucess
    (get token dataDecoder "/api/data")
post : Token -> Decoder a -> String -> Body -> Task Error a

post is a replacement for Http.post that attaches a provided Jwt token to the headers, and sets the Content-type to 'application/json'.

getWithJwt : Token -> Decoder a -> String -> Task Error a

getWithJwt is an alias for get, provided for backwards compatibility.

isExpired : Time -> Token -> Bool

isExpired checks whether a token remains valid, i.e. it has not expired.

Note: This function assumes that the expiry was set in seconds and thus multiplies by 100 to compare with javascript time (in milliseconds). You may need to write a custom version if your Jwt provide works differently.

promote401 : Token -> Error -> Task JwtError a

promote401 promotes a 401 Unauthorized Http reponse to the JwtError TokenExpired.

Jwt.get token dataDecoder "/api/data"
`Task.onError` (promote401 token)
|> Task.perform PostFail PostSucess

Errors

= HttpError Error
| TokenExpired
| TokenProcessingError String
| TokenDecodeError String

The three errors that can emerge are:

  • network errors (except a 401),
  • a 401 error, which we check is because of token expiry
  • issues with processing (e.g. base 64 decoding) the token, and
  • problems decoding the json data within the content of the token