Skip to content

jim108dev/purescript-node-jwt

 
 

Repository files navigation

purescript-node-jwt

Safe bindings for the Node JWT module. Allows to sign, decode, and verify tokens.

Installation

spago install node-jwt

Example

This library adheres to the JWT RFC, so in the below examples, headers is JOSE Header, and claims is, well, Claims.

Sign

To sign a project, you'll need to provide a secret key, some headers, and some claims. The sign function will return an Aff String.

sign
  (Secret "my-super-secret-key")
  defaultHeaders
  defaultClaims

By default, some values will be set for you: alg will be HS256, typ equals JWT, and the iat field will be set to the creation timestamp. You can override any for the above by providing the value explicitely.

You can also provide an unregisteredClaims record, each values of that record must be encodable:

sign
  (Secret "my-super-secret-key")
  defaultHeaders
  (defaultClaims { unregisteredClaims = Just { foo: "bar" } )

Decode

If decode succeeds, it will return a Token r Unverified where r is the row type of the unregisteredClaims record. You can read the headers and claims as follow:

decodedHeaders :: String -> Maybe JOSEHeaders
decodedHeaders token = hush $ decode' token <#> _.headers

decodedClaims :: String -> Maybe (Claims ())
decodedClaims token = hush $ decode' token <#> _.claims

decodedClaims' :: String -> Maybe (Claims ( foo :: String ))
decodedClaims' token = hush $ decode token <#> _.claims

Notice that when decoding claims with some explicit unregistered claims, said claims must be of the expected type at runtime.

Verify

If verify succeeds, it will return a Token Verified you can read the headers and claims this way:

verifiedHeaders :: String -> Maybe JOSEHeaders
verifiedHeaders token = hush $ verify' (Secret "my-super-secret-key") token <#> _.headers

verifiedClaims :: String -> Maybe (Claims ())
verifiedClaims token = hush $ verify' (Secret "my-super-secret-key") token <#> _.claims

verifiedClaims' :: String -> Maybe (Claims ( foo :: String ))
verifiedClaims' token = hush $ verify (Secret "my-super-secret-key") token <#> _.claims

Documentation

Module documentation is published on Pursuit.

About

Safe bindings for the Node JWT module

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PureScript 75.8%
  • Dhall 17.1%
  • JavaScript 7.1%