Giter Site home page Giter Site logo

elm-jwt's Introduction

Elm helpers for working with Jwt tokens.

A collection of functions to decode Jwt tokens, and to use them for authenticated CRUD requests.

Decode a token

A Jwt is a Base64 string that has three parts

  • header
  • content
  • signature

The library functions decodeToken and tokenDecoder provide the means to decode the content of a token, while checkTokenExpiry and isExpired specifically analyse whether the token remains within its expiry time.

Make an authenticated CRUD request

The library also provides modified versions of thet standard Http functions to make CRUD requests with the Authorization header set to "bearer "

let
    url =
        "http://example.com/new"
    body =
        Http.jsonBody <some Value>
in
    Jwt.Http.post token { url = url, body = body, expect = Http.expectJson OnData (Json.Decode.field "confirmation" Json.Decode.string) }

Examples

An example with a Node backend is provided.

I previous blogged about using elm-jwt with Phoenix.

Changelog

  • 7.1.1: (0.19.1) Use faster Base64 library (thanks Petre)
  • 7.1.0: (0.19) Expose getTokenExpirationMillis (thanks robx)
  • 7.0.0: (0.19) Http 2.0.0 necessitated major changes. I took the opportunity to simplify my code and the JwtError type in particular. All token processing functions now also do a cursory check that the header is valid json
  • 6.0.0: (0.19) Update
  • 5.3.0: Adds decoder got Elixir-Guardian token
  • 5.2.0: Update NodeJS example
  • 5.1.0: Adds a decoder for the Firebase Jwt.
  • 5.0.0 (0.18): Corrects a typo in name of checkTokenExpiry and separates out createRequestObject
  • 4.0.0 (0.18): Elm's Http library has undergone a major rewrite for 0.18 and this library depends upon it. As a result much has changed and you are encouraged to re-look at the examples and the docs.
  • 3.0.0 (0.18): Elm 0.17 users should use version 2.0.0.
  • 2.0.0 (0.17): The one breaking change is that authenticate now returns Task JwtError String rather than Task never (Result JwtError String). It is better to leave it to the user to handle the conversion to a Cmd. Elm 0.16 users should use version 1.0.2.

elm-jwt's People

Contributors

elm-review-bot avatar finlay avatar pdamoc avatar perry-birch avatar robx avatar simonh1000 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

elm-jwt's Issues

Examples included under elm-stuff/

I just set up a phoenix project to try out jwt and I get the following error:
'== Compilation error on file lib/tinker_web/web/elm/elm-stuff/packages/simonh1000/elm-jwt/5.0.0/examples/phoenix/web/gettext.ex ==
warning: no configuration found for otp_app :jwt_example and module JwtExample.Endpoint
** (ArgumentError) unknown application: :jwt_example'

All though this was a good thing for me since I hadn't yet discovered the examples, they probably shouldn't be included in elm-stuff/ when building. (Had I placed my Elm code outside Phoenix it would be different of course.)

0.19

Any plans to update to 0.19?

Request.withCredentials is not set to true

{-| createRequest creates a Http.Request with the token added to the headers, and
sets the `withCredentials` field to True.
-}
createRequest : String -> String -> String -> Http.Body -> Json.Decoder a -> Request a
createRequest method token url body dec =
    request
        { method = method
        , headers =
            [ header "Authorization" ("Bearer " ++ token) ]
        , url = url
        , body = body
        , expect = expectJson dec
        , timeout = Nothing
        , withCredentials = False
        }

The comment seems to contradict the source code.

Using package with Elm inside a Phoenix app

This is not really an error but more of an FYI.

The alternative to having Elm as it's own separate app is to add Elm into the Phoenix project itself (./web/elm is the currently favored directory) and add brunch-elm or use webpack instead of brunch. This causes a problem because mix wants to compile the example program from this package (which generates some errors). By default mix is going to include anything in the web directory and try and compile it.

For those coming to this via a google search. The better way to handle this is to use ./elm instead of ./web/elm inside your phoenix app. Which does require some changes to brunch or web pack config besides just moving the directory.

JWT uses base64url encoding, not base64 encoding

base64 and base64url encoding are different in the last two characters used,
ie, base64 -> '+/', or base64url -> '-_'
see https://en.wikipedia.org/wiki/Base64#URL_applications

To make the decode Jwt.decodeToken function work I needed to add this simple function to pre-process the token:

unurl = 
    let fix c = 
          case c of 
            '-' -> '+'
            '_' -> '/'
            c   -> c
    in String.map fix

Then it works great.

This fix could be added to the elm-jwt library, or the base64 library expanded to include a urldecode version.

variant of expiry check helpers that exposes remaining time?

I'd like to check not just whether a token is expired, but whether it's close to expiry. To that extent, an API like the following would be great (which would easily allow implementing the current specialized functions):

getTokenExpirationMillis : String -> Result JwtError Int
getTokenExpirationMillis = ...

getTokenTimeToExpirationMillis : String -> Task JwtError Int
getTokenTimeToExpirationMillis = ...

What do you think? I'd be happy to provide a PR if you think this is a good idea.

Examples not working

Hi

I cloned this repo and ran the npm install and gulp - but the elm does not compile:

-- NAMING ERROR -------------------------------------------------- ./src/App.elm

Cannot find variable `Jwt.checkTokenExpirey`.

138|             , Jwt.checkTokenExpirey token
                   ^^^^^^^^^^^^^^^^^^^^^
`Jwt` does not expose `checkTokenExpirey`. Maybe you want one of the following?

    Jwt.checkTokenExpiry

-- NAMING ERROR -------------------------------------------------- ./src/App.elm

This usage of variable `tokenDecoder` is ambiguous.

237|                         decodeToken tokenDecoder tokenString
                                         ^^^^^^^^^^^^
Maybe you want one of the following?

    Decoders.tokenDecoder
    Jwt.tokenDecoder

the first looks like a spelling mistake where checkTokenExpiry is spelled incorrectly - and the second one I'm not sure whether it should be decoding from Jwt or Decoders?

Discussion: provide functions for split JWT token headers

Hi! Recently a colleague split the bearer token because of some security reasons, thus I ended up having to do this in all my HTTP calls:

                , headers =
                    [ Http.header "x-signature-token" tokens.signatureToken
                    , Http.header "x-header-payload-token" tokens.headerPayloadToken
                    ]

Does it make sense to add Http.{get|delete|put|post} function libs to support that use case to this library? ๐Ÿค”

204 response from API

Hi,

Thanks for this package ๐Ÿ‘

My API gives a 204 response with no content, but this throw an HttpError:

HttpError (BadPayload "Given an invalid JSON: Unexpected end of JSON input" { status = { code = 204, message = "No Content" }, headers = Dict.fromList [("Content-Type","text/html; charset=UTF-8")], url = "http://madeupurl.com", body = "" })

Do you have any suggestions for how to handle this? I have tried this but still get the same error:

emptyDecoder : Json.Decoder String
emptyDecoder =
    Json.value |> Json.andThen (\_ -> Json.succeed "true")

How are we supposed to include csrf headers?

Would it be a good idea to add an extra argument to the authenticate method, or maybe set some kind of default to include or add the csrf header to the elm http send request.

Right now it looks like i have to modify the JWT library itself to add in my csrf token header.

Tests?

Hi, I saw your lib and found that there is 0 tests.

please provide a documented, generic alias to `firebase`

I'd like to reuse the firebase decoder for a generic JWT-authenticated backend (postgrest specifically), which uses the standard exp, iat, user_id fields. However, this feels wrong with the existing API, because:

  • it's not firebase
  • the API docs don't state what the JWT is actually expected to look like

I'd suggest defining generic = firebase and documenting the behaviour of generic. What do you think?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.