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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Any user-supplied redirect target must be validated against an allowlist before you trust it.
  2. 2Storing the return path in the session lets you resume a user's intended destination after authentication.
  3. 3Parsing a redirect with URI and checking host and path shape defends against protocol-relative and off-site redirects.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Safe post-login redirects in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code