Authex is a simple JWT authentication and authorization library for Elixir.
The package can be installed by adding authex to your list of dependencies in mix.exs.
In addition, we must also add a JSON encoder/decoder. Jason is recommended. But any of these will work: jiffy, jsone, jsx, ojson, Poison.
Finally, if you wish to use any of the plug functionality, make sure to add the plug dependency.
defdepsdo[{:authex,"~> 2.0"},{:jason,"~> 1.0"},{:plug,"~> 1.0"}]endSee HexDocs for additional documentation.
To get started, we must define our auth module:
defmoduleMyApp.AuthdouseAuthexdefstart_link(opts\\\\[])doAuthex.start_link(__MODULE__,opts,name: __MODULE__)end# Callbacks@implAuthexdefinit(opts)do# Add any configuration listed in Authex.start_link/3secret=System.get_env("AUTH_SECRET")||"foobar"opts=Keyword.put(opts,:secret,secret){:ok,opts}end@implAuthexdefhandle_for_token(%MyApp.User{}=resource,opts)do{:ok,[sub: resource.id,scopes: resource.scopes],opts}enddefhandle_for_token(_resource,_opts)do{:error,:bad_resource}end@implAuthexdefhandle_from_token(token,_opts)do# You may want to perform a database lookup for your user instead{:ok,%MyApp.User{id: token.sub,scopes: token.scopes}}endendAnd add it to your supervision tree:
children=[MyApp.Auth]We can then create, sign, and verify tokens:
token=Authex.token(MyApp.Auth,sub: 1,scopes: ["admin/read"])compact_token=Authex.sign(MyApp.Auth,token){:ok,token}=Authex.verify(MyApp.Auth,compact_token)We can also convert resources to and from tokens.
token=Authex.for_token(MyApp.Auth,user)compact_token=Authex.sign(MyApp.Auth,token){:ok,token}=Authex.verify(MyApp.Auth,compact_token){:ok,user}=Authex.from_token(MyApp.Auth,token)Please check out the documentation for more advanced features.
- Easy to integrate with almost any app.
- Handles both authentication + authorization.
- Convert data to and from tokens.
- Handle persistence for things like blacklists.
- Batteries included for plug integration.