Skip to content

Instantly share code, notes, and snippets.

# Pipeline for private apis, requires Authorisation header with Bearer token
pipeline :private do
plug :accepts, ["json"]
plug Auth.Guardian.Pipeline
end
defmodule Auth.Guardian.Pipeline do
@moduledoc """
Configures a set of plugs to be used with Guardian based authentication / authorisation
"""
use Guardian.Plug.Pipeline,
otp_app: :orders,
error_handler: Auth.Guardian.ErrorHandler,
module: Auth.Guardian
# Verify authorisation header and make sure order management is allowed for Identity
# Setup Guardian with Auth0
config :orders, Auth.Guardian,
allowed_algos: ["HS256"],
verify_module: Guardian.JWT,
issuer: "https://orders-sample.eu.auth0.com/",
verify_issuer: true,
secret_key: "qgXw5waJYQ8kd6LDFpqY4UuswJ4D0gGS"
defmodule Auth.Identity do
@moduledoc """
This struct represents the Identitiy accessible on each connection
"""
@enforce_keys [:id]
defstruct id: nil
@type t() :: [
id: String.t()
]
defmodule Auth.Guardian do
@moduledoc """
This is the main Guardian module used by the application to gain access to claims,
identity, token, etc.
Implements callback to properly integrate with Auth0.
"""
use Guardian, otp_app: :orders
alias Auth.Identity
defmodule OrdersWeb.AuthController do
@moduledoc """
This controller allows retrieving an access token from auth0 and returning it to the user
providing username / password based login capability
"""
use OrdersWeb, :controller
alias Auth
alias Auth.{Credentials, TokenResult}
defmodule Auth do
@moduledoc """
This module is responsible to authenticate client credentials against Auth0
and provide access_token and expires_in as a result
"""
alias Auth.{Credentials, TokenResult}
import Base
require Logger
@zoltanarvai
zoltanarvai / token_result.ex
Created March 23, 2019 11:05
Struct to encompass token and other meta info
defmodule Auth.TokenResult do
@moduledoc """
This struct represents the result of the authentication sign-in process.
We get a JWT access token from Auth0 and an expires_in field explaining
how long the token field will be available
"""
@enforce_keys [:access_token, :expires_in]
defstruct access_token: "", expires_in: 0
@type t :: %__MODULE__{
defmodule Auth.Credentials do
@moduledoc """
This module represents and validates the credentials
"""
use Ecto.Schema
import Ecto.Changeset
alias Auth.Credentials
@primary_key false
@zoltanarvai
zoltanarvai / dev.exs
Last active March 23, 2019 10:43
Dev configuration for Auth0
# Configure auth zero for the Auth module
config :orders,
auth0: %{
url: %URI{
host: "orders-sample.eu.auth0.com",
port: 443,
scheme: "https"
},
client_id: "6NeT3VHSzKK4mMXVq7BhSvAq0fUSUXUB",
client_secret: "9aAIvTnSL-09QyP-ttbxy9l0NavpyySHulTMTqUYpyfTG0Clt8qz1IEAcqN5spy6",