ruby
49 lines · 9 steps
Safe post-login redirects in Rails
Store where a user was headed before login and validate it against an allowlist so attackers can't redirect them off-site.
Explained by
highlit
1class ApplicationController < ActionController::Base
2 ALLOWED_REDIRECT_HOSTS = [nil, ENV.fetch("APP_HOST", "app.example.com")].freeze
3
4 def store_return_to(location = request.fullpath)
5 return unless request.get? && !request.xhr?
6
7 session[:return_to] = location if safe_redirect?(location)
8 end
9
10 def stored_location_for(_resource = nil)
11 location = session.delete(:return_to)
12 location if location.present? && safe_redirect?(location)
13 end
14
15 def redirect_back_after_login(resource)
16 redirect_to(stored_location_for(resource) || signed_in_root_path(resource))
17 end
18
19 private
20
21 def safe_redirect?(location)
22 uri = URI.parse(location.to_s)
23 return false if uri.path.blank?
24 return false if uri.path.start_with?("//")
25
26 ALLOWED_REDIRECT_HOSTS.include?(uri.host)
27 rescue URI::InvalidURIError
28 false
29 end
30end
31
32class SessionsController < ApplicationController
33 def new
34 store_return_to(params[:return_to].presence || request.referer)
35 end
36
37 def create
38 user = User.authenticate_by(email: params[:email], password: params[:password])
39
40 if user
41 reset_session
42 sign_in(user)
43 redirect_back_after_login(user)
44 else
45 flash.now[:alert] = "Invalid email or password."
46 render :new, status: :unprocessable_entity
47 end
48 end
49end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Any user-supplied redirect target must be validated against an allowlist before you trust it.
- 2Storing the return path in the session lets you resume a user's intended destination after authentication.
- 3Parsing a redirect with URI and checking host and path shape defends against protocol-relative and off-site redirects.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
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/safe-post-login-redirects-in-rails-explained-ruby-5866/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.