Skip to content

primait/auth0_ex

Folders and files

NameName
Last commit message
Last commit date

Latest commit

96eeff1 · Aug 30, 2023
Apr 29, 2021
Aug 25, 2023
Nov 30, 2021
Aug 30, 2023
Aug 25, 2023
Jan 10, 2022
Mar 22, 2021
Nov 30, 2021
Apr 12, 2021
Feb 23, 2021
Aug 5, 2022
Aug 30, 2023
Aug 5, 2022
Feb 2, 2023
Nov 30, 2021
Aug 24, 2023
Mar 1, 2022
Jan 19, 2022
Aug 24, 2023
Aug 30, 2023
Aug 28, 2023

Repository files navigation

prima_auth0_ex

Module Version Hex Docs Total Download License Last Updated

An easy-to-use library to authenticate machine-to-machine communications through Auth0.

Supports both retrieval of JWTs and their verification and validation.

Table of contents

Installation

The package can be installed by adding prima_auth0_ex to your list of dependencies in mix.exs:

def deps do
  [
    {:prima_auth0_ex, "~> 0.6.0"}
  ]
end

Configuration

prima_auth0_ex can be configured to be used for an API consumer, an API provider or both.

API Consumer

To configure the library for use from a client (i.e. a service that needs to obtain tokens to access some API), the following configuration is supported:

config :prima_auth0_ex, :clients, default_client: [
  # Base url for Auth0 API
  auth0_base_url: "https://tenant.eu.auth0.com"
  # Credentials on Auth0
  client_id: "",
  client_secret: "",
  # Namespace for tokens of this client on the shared cache. Should be unique per client
  cache_namespace: "my-client"
]

If the client will access APIs that perform validation of permissions, make sure that the API on Auth0 is configured to have both "Enable RBAC" and "Add Permissions in the Access Token" enabled. Otherwise, the JWTs generated by Auth0 may not include the necessary permissions claims.

A visualization of the logic behind the TokenProvider is available here.

Multiple clients

If you need to use multiple clients which target different Auth0 instances, you can configure them like so

config :prima_auth0_ex, :clients, your_client_name: [
  # Base url for Auth0 API
  auth0_base_url: "https://tenant.eu.auth0.com"
  # Credentials on Auth0
  client_id: "",
  client_secret: "",
  # Namespace for tokens of this client on the shared cache. Should be unique per client
  cache_namespace: "my-client"
]

You can configure multiple :clients, the name is arbitrary and the only requirement is that it be unique.

API Provider

To configure the library for use from a server (ie. a service that exposes an API), the following configuration is supported:

config :prima_auth0_ex, :server,
  # Base url for Auth0 API
  auth0_base_url: "https://your-tenant.eu.auth0.com/",
  # Default audience used to verify tokens. Not necessary when audience is set explicitly on usage.
  audience: "audience",
  # Issuer used to verify tokens. Can be found at https://your-tenant.eu.auth0.com/.well-known/openid-configuration
  issuer: "https://tenant.eu.auth0.com/",
  # Whether to perform the first retrieval of JWKS synchronously. Defaults to true.
  first_jwks_fetch_sync: true,
  # When true, logs errors in validation of tokens, but it does not stop the request when the token is not valid.
  # Defaults to false.
  dry_run: false,
  # When true, only the claims of tokens are validated, but their signature is not verified.
  # This is useful for local development but should NEVER be enabled on production-like systems.
  # Defaults to false.
  ignore_signature: false,
  # Level used to log requests where the authorization header is missing. 
  missing_auth_header_log_level: :warn

Redis & caching

Clients can be configured to use caching through Redis. To use cachine you can use the following configuration:

config :prima_auth0_ex, :redis,
  # Enables cache on redis for tokens obtained from Auth0. Defaults to false.
  enabled: true,
  # AES 256 key used to encrypt tokens on the shared cache.
  # Can be generated via `:crypto.strong_rand_bytes(32) |> Base.encode64()`.
  encryption_key: "uhOrqKvUi9gHnmwr60P2E1hiCSD2dtXK1i6dqkU4RTA=",
  connection_uri: "redis://redis:6379",
  # Read here for more infos: https://hexdocs.pm/redix/Redix.html#module-ssl
  ssl_enabled: false,
  ssl_allow_wildcard_certificates: false

Note that right now caching is assumed to be all-or-nothing with respect to multiple clients i.e. either all clients use caching or none of them do. If you have a use case that is not supported by this please contact us so that we can see what we can do.

Operational requirements

To cache tokens on Redis you'll need to generate a cache_encryption_key. This can be done either by running mix keygen or by using the following snippet:

:crypto.strong_rand_bytes(32) |> Base.encode64()

Alternatively you can generate it on command line (Linux/MacOSX) with:

dd if=/dev/random bs=1 count=32 | base64

⚠️ The token needs to be 32 bytes long AND base64 encoded, failing to do so will result in tokens not getting cached on Redis. ⚠️

Usage

Obtaining tokens

Tokens for a given audience can be obtained as follows:

{:ok, token} = PrimaAuth0Ex.token_for("target-audience")

This call will target the :default_client, assuming it's configured.

Instead, if you want to obtain a token for a specific client you can do it like so:

{:ok, token} = PrimaAuth0Ex.token_for("target-audience", :target_client)

Tokens are automatically refreshed when they expire and when the signing keys are revoked. It is also possible to force the refresh of the token, both on the local instance and on the shared cache, as follows:

# With the default client
{:ok, new_token} = PrimaAuth0Ex.refresh_token_for("target-audience")

# With a specific client
{:ok, new_token} = PrimaAuth0Ex.refresh_token_for("target-audience", :target_client)

A use-case for forcing the refresh of the token may be e.g. if new permissions are added to an application on Auth0, and we want to propagate this change without waiting for the natural expiration of tokens.

Verifying tokens

Tokens can be verified and validated as follows:

{:ok, claims} = PrimaAuth0Ex.verify_and_validate("my-token")

The audience and the required permissions can be explicitly specified:

{:ok, claims} = PrimaAuth0Ex.verify_and_validate("my-token", "my-audience", ["required-permission1"])

For Plug-based applications, a plug to automate this process is available:

plug PrimaAuth0Ex.Plug.VerifyAndValidateToken

This will return 401 Forbidden to requests without a valid bearer token.

The plug supports the following options:

  • audience: "my-audience" to explicitly set the expected audience. When not defined it defaults to the audience configured in :prima_auth0_ex, :server, :audience;
  • required_permissions: ["p1", "p2"] to forbid access to users who do not have all the required permissions;
  • dry_run to allow access to the API when the token is not valid (mostly useful for testing purposes).

Validating permissions with Absinthe

To validate permissions in your Graphql API on a per-query/per-mutation basis, an option is to define an Absinthe middleware. To this end, you can use the PrimaAuth0Ex.Absinthe.RequirePermissions included with the library or build your own.

This middleware has a companion plug: PrimaAuth0Ex.Absinthe.CreateSecurityContext, which can be used to pass the user's permissions to the Absinthe context.

It is important to note that the middleware will only validate permissions: other validations and the verification of the signature will still need to be done elsewhere (e.g. using the aforementioned plug).

The middleware can be used in your schema as follows:

field ... do
  middleware RequirePermissions, ["your-required-permission"]
  resolve &Resolver.resolve_function/3

Metrics

prima_auth0_ex uses :telemetry to emit two events

  • [:prima_auth0_ex, :retrieve_token, :success]
  • [:prima_auth0_ex, :retrieve_token, :failure]

which represent a successful or failed attempt to fetch a new JWT from Auth0.

If you want to leverage them you can

The pre-defined handler tries to be as agnostic as possible from the underlying reporter and it can be configured by setting the following

config :prima_auth0_ex, telemetry_reporter: TelemetryReporter

At startup, the library will check if a reporter has been configured and then it will attach it as a handler.

To work, the reporter needs to have an increment method like in Statix or Instruments, and it will then increment one of two counters: auth0.token. Each counter will be tagged by audience and status (success or failure).

Development

The test suite can be executed as follows:

mix test

By default tests that integrate with Auth0 are excluded. To run them, configure your auth0 credentials and audience in config/test.exs and run:

mix test --include external

Always run formatter, linter and dialyzer before pushing changes:

mix check