ruby
36 lines · 6 steps
JWT authentication as a Rails concern
A reusable concern that decodes a bearer token, loads the current user, and rejects bad tokens with clean JSON errors.
Explained by
highlit
1module Authenticatable
2 extend ActiveSupport::Concern
3
4 included do
5 before_action :authenticate_request!
6 attr_reader :current_user
7 end
8
9 private
10
11 def authenticate_request!
12 payload = decode_token(bearer_token)
13 @current_user = User.find(payload[:sub])
14 rescue JWT::ExpiredSignature
15 render json: { error: "Token has expired" }, status: :unauthorized
16 rescue JWT::DecodeError, ActiveRecord::RecordNotFound
17 render json: { error: "Invalid or missing token" }, status: :unauthorized
18 end
19
20 def bearer_token
21 header = request.headers["Authorization"]
22 raise JWT::DecodeError, "Missing Authorization header" if header.blank?
23
24 header.split(" ").last
25 end
26
27 def decode_token(token)
28 decoded, = JWT.decode(
29 token,
30 Rails.application.credentials.jwt_secret,
31 true,
32 algorithm: "HS256"
33 )
34 decoded.deep_symbolize_keys
35 end
36end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1ActiveSupport::Concern lets you inject callbacks and shared behavior into any controller that includes it.
- 2Rescuing specific token exceptions maps failure modes to precise 401 responses instead of leaking stack traces.
- 3Memoizing the authenticated user in @current_user gives every action access to who is making the request.
Related explainers
ruby
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/jwt-authentication-as-a-rails-concern-explained-ruby-e0e5/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.