Helper functions for working with Jwt tokens and authenticated CRUD APIs.
This package provides functions for reading tokens, and for using them to make authenticated Http requests.
All the token parsing goodness in the form of a Json Decoder
-- decode token from Firebase
let firebaseToken =
decodeString (tokenDecoder Jwt.Decoders.firebase) tokenStringChecks whether a token has expired, and returns True or False, or any error that occurred while decoding the token.
Checks a token for Expiry. Returns expiry or any errors that occurred in decoding.
createRequest creates a Http.Request with the token added to the headers, and
sets the withCredentials field to True.
createRequestObject creates the data structure expected by Http.Request. It is broken out here so that users can change the expect part in the event that one of their REST apis does not return Json.
In my experience, the Authorization header is NOT case sensitive. Do raise an issue if you experience otherwise.
See MDN for more on withCredentials. The default is False.
send replaces Http.send. On receipt of a 401 error, it returns a Jwt.Unauthorized.
sendCheckExpired is similar to send but, on receiving a 401, it carries out a further check to
determine whether the token has expired.
get is a replacement for Http.get that returns a Http.Request with the token
attached to the headers.
getData : String -> Cmd Msg
getData token =
Jwt.get token "/api/data" dataDecoder
|> Jwt.send DataResultpost is a replacement for Http.post that returns a Http.Request with the token
attached to the headers.
** Note that is important to use jsonBody to ensure that the 'application/json' is added to the headers **
postContent : Token -> Decoder a -> E.Value -> String -> Request a
postContent token dec value url =
Jwt.post token url (Http.jsonBody value) (phoenixDecoder dec)
|> Jwt.send ContentResultCreate a PUT request with a token attached to the Authorization header
returns a DELETE Http.Request with the token attached to the headers.
The following errors are modeled
Examines a 401 Unauthorized reponse, and converts the error to TokenExpired when that is the case.
getAuth : String -> String -> Decoder a -> Task Never (Result JwtError a)
getAuth token url dec =
createRequest "GET" token url Http.emptyBody dec
|> toTask
|> Task.map Result.Ok
|> Task.onError (promote401 token)Takes an Http.Error. If it is a 401, check the token for expiry.
decodeToken parses the token, checking that it meets the Jwt standards.
In the event of success,
decodeTokenreturns an Elm record structure using the JSON Decoder.