ApiAuthentication
Token authentication Plug for Phoenix.
Installation
If available in Hex, the package can be installed
by adding api_authentication to your list of dependencies in mix.exs:
def deps do
[
{:api_authentication, "~> 0.1.0"}
]
endConfiguration
config :api_authentication, ApiAuthentication,
repo: MyApp.Repo,
schema_name: "tokens", # default
resource_fk: :user_id, # default
expire: 3600, # default You will need to create a migration for the Tokens database table:
defmodule TokenAuth.Repo.Migrations.CreateAuthenticationTokens do
use Ecto.Migration
def change do
create table(:tokens) do
add :secret_id, :string
add :hashed_secret, :string
add :expires, :integer
add :user_id, references(:users, on_delete: :nothing)
timestamps()
end
create index(:tokens, [:user_id])
create unique_index(:tokens, [:secret_id])
end
endUse the plug in your application entrypoint
defmodule MyApp do
def controller do
quote do
...
import ApiAuthentication, only: [authenticate_request: 2]
...
end
end
endYou can use the plug in your controller:
defmodule MyApp.ProtectedController do
plug :authenticate_request when action in [:index]
endAdd the plug to your controller:
defmodule MyApp.Router do
pipeline :api do
plug ApiAuthentication, repo: MyApp.Repo
end
end