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 'set' class DirectoryWatcher def initialize(path, pattern: '**/*', interval: 1.0)
Polling for file changes in Ruby
polling
filesystem
diffing
Intermediate
7 steps
ruby
class HashDiff Change = Struct.new(:from, :to) def self.call(before, after)
Diffing two hashes in Ruby
set-operations
struct
enumerable
Intermediate
7 steps
php
final class FieldEncryptor { private string $key;
Authenticated field encryption with libsodium
encryption
libsodium
authenticated-encryption
Intermediate
7 steps
ruby
module CreditCard module_function def valid?(number)
Validating credit card numbers with Luhn
checksum
luhn-algorithm
validation
Intermediate
6 steps
ruby
class UserColor GOLDEN_RATIO_CONJUGATE = 0.618033988749895 def initialize(username)
Deriving a stable color from a username
hashing
color-theory
deterministic-mapping
Intermediate
7 steps
ruby
namespace :counter_cache do desc "Recalculate comments_count for posts after a backfill" task warm_post_comments: :environment do scope = Post.where(comments_count: nil).or(Post.where("comments_count < 0"))
Backfilling counter caches in a Rake task in Rails
counter-cache
batching
rake-tasks
Intermediate
6 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.