|
| 1 | +# Auth Plugins |
| 2 | + |
| 3 | +This document provides an example of how to implement a custom authentication plugin for a hypothetical system. The plugin checks for a specific authorization header and validates it against a secret stored in an environment variable. |
| 4 | + |
| 5 | +In your global configuration file (e.g. `hooks.yml`) you would likely set `auth_plugin_dir` to something like `./plugins/auth`. |
| 6 | + |
| 7 | +Here is an example snippet of how you might configure the global settings in `hooks.yml`: |
| 8 | + |
| 9 | +```yaml |
| 10 | +# hooks.yml |
| 11 | +auth_plugin_dir: ./plugins/auth # Directory where custom auth plugins are stored |
| 12 | +``` |
| 13 | +
|
| 14 | +Then place your custom auth plugin in the `./plugins/auth` directory, for example `./plugins/auth/some_cool_auth_plugin.rb`. |
| 15 | + |
| 16 | +```ruby |
| 17 | +# frozen_string_literal: true |
| 18 | +# Example custom auth plugin implementation |
| 19 | +module Hooks |
| 20 | + module Plugins |
| 21 | + module Auth |
| 22 | + class SomeCoolAuthPlugin < Base |
| 23 | + def self.valid?(payload:, headers:, config:) |
| 24 | + # Get the secret from environment variable |
| 25 | + secret = fetch_secret(config) # by default, this will fetch the value of the environment variable specified in the config (e.g. SUPER_COOL_SECRET as defined by `secret_env_key`) |
| 26 | + |
| 27 | + # Get the authorization header (case-insensitive) |
| 28 | + auth_header = nil |
| 29 | + headers.each do |key, value| |
| 30 | + if key.downcase == "authorization" |
| 31 | + auth_header = value |
| 32 | + break |
| 33 | + end |
| 34 | + end |
| 35 | + |
| 36 | + # Check if the header matches our expected format |
| 37 | + return false unless auth_header |
| 38 | + |
| 39 | + # Extract the token from "Bearer <token>" format |
| 40 | + return false unless auth_header.start_with?("Bearer ") |
| 41 | + |
| 42 | + token = auth_header[7..-1] # Remove "Bearer " prefix |
| 43 | + |
| 44 | + # Simple token comparison (in practice, this might be more complex) |
| 45 | + token == secret |
| 46 | + end |
| 47 | + end |
| 48 | + end |
| 49 | + end |
| 50 | +end |
| 51 | +``` |
| 52 | + |
| 53 | +Then you could create a new endpoint configuration that references this plugin: |
| 54 | + |
| 55 | +```yaml |
| 56 | +path: /example |
| 57 | +handler: CoolNewHandler |
| 58 | + |
| 59 | +auth: |
| 60 | + type: some_cool_auth_plugin # using the newly created auth plugin as seen above |
| 61 | + secret_env_key: SUPER_COOL_SECRET # the name of the environment variable containing the shared secret - used by `fetch_secret(config)` in the plugin |
| 62 | + header: Authorization |
| 63 | +``` |
0 commit comments