Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

passwordless

> 后端框架
Open source

Authentication for your Rails app without the icky-ness of passwords

1.3K stars0 likes1 views
WebsiteGitHub

About

Authentication for your Rails app without the icky-ness of passwords

Add authentication to your Rails app without all the icky-ness of passwords. Magic link authentication, if you will. We call it passwordless.

  • Installation
    • Upgrading
  • Usage
    • Getting the current user, restricting access, the usual
    • Providing your own templates
    • Registering new users
    • URLs and links
    • Route constraints
  • Configuration
    • Delivery method
    • Token generation
    • Timeout and Expiry
    • Redirection after sign-in
    • Looking up the user
  • Test helpers
  • Security considerations
  • Alternatives
  • License

Installation

Add to your bundle and copy over the migrations:

bash
$ bundle add passwordless
$ bin/rails passwordless_engine:install:migrations

Upgrading

See Upgrading to Passwordless 1.0 for more details.

Usage

Passwordless creates a single model called Passwordless::Session, so it doesn't come with its own user model. Instead, it expects you to provide one, with an email field in place. If you don't yet have a user model, check out the wiki on creating the user model.

Enable Passwordless on your user model by pointing it to the email field:

ruby
class User  # => /users/sign_in

passwordless_for :users, at: '/', as: :auth
  #  # => /sign_in

Also be sure to specify ActionMailer's default_url_options.host and tell the routes as well:

ruby
# config/application.rb for example:
config.action_mailer.default_url_options = {host: "www.example.com"}
routes.default_url_options[:host] ||= "www.example.com"

Note as well that passwordless_for accepts a custom controller. One possible application of this is to add a before_action that redirects authenticated users from the sign-in routes, as in this example:

ruby
# config/routes.rb
passwordless_for :users, controller: "sessions"
ruby
# app/controllers/sessions_controller.rb

class SessionsController  (user) { user.email.include?("john") }) do
  # ...
end

The negated version has the same API but with the opposite result, ie. ensuring authenticated user don't have access:

ruby
constraints Passwordless::ConstraintNot.new(User) do
  get("/no-users-allowed", to: "secrets#index")
end

Configuration

To customize Passwordless, create a file config/initializers/passwordless.rb.

The default values are shown below. It's recommended to only include the ones that you specifically want to modify.

…

Delivery method

By default, Passwordless sends emails. See Providing your own templates. If you need to customize this further, you can do so in the after_session_save callback.

In config/initializers/passwordless.rb:

ruby
Passwordless.configure do |config|
  config.after_session_save = lambda do |session, request|
    # Default behavior is
    # Passwordless::Mailer.sign_in(session, session.token).deliver_now

    # You can change behavior to do something with session model. For example,
    # SmsApi.send_sms(session.authenticatable.phone_number, session.token)
  end
end

After Session Confirm Hook

An after_session_confirm hook is called after a successful session confirmation – in other words: after a user signs in successfully.

ruby
Passwordless.configure do |config|
  config.after_session_confirm = ->(session, request) {
    user = session.authenticatable
    user.update!(
      email_verified: true,
      last_login_ip: request.remote_ip
    )
  }
end

Token generation

By default Passwordless generates short, 6-digit, alpha numeric tokens. You can change the generator using Passwordless.config.token_generator to something else that responds to call(session) eg.:

ruby
Passwordless.configure do |config|
  config.token_generator = lambda do |session|
    "probably-stupid-token-#{session.user_agent}-#{Time.current}"
  end
end

Passwordless will keep generating tokens until it finds one that hasn't been used yet. So be sure to use some kind of method where matches are unlikely.

Timeout and Expiry

The timeout is the time by which the generated token and magic link is invalidated. After this the token cannot be used to sign in to your app and the user will need to request a new token.

The expiry is the expiration time of the session of a logged in user. Once this is expired, the user is signed out.

Note: Passwordless' session relies on Rails' own session and so will never live longer than that.

To configure your Rails session, in config/initializers/session_store.rb:

ruby
Rails.application.config.session_store :cookie_store,
  expire_after: 1.year,
  # ...

Redirection after sign-in

By default Passwordless will redirect back to where the user wanted to go if it knows where that is -- so you'll have to help it. Passwordless::ControllerHelpers provide a method:

ruby
class ApplicationController < ActionController::Base
  include Passwordless::ControllerHelpers # <-- Probably already have this!

  # ...

  def require_user!
    return if current_user
    save_passwordless_redirect_location!(User) # <-- this one!
    redirect_to root_path, alert: "You are not worthy!"
  end
end

This can also be turned off with Passwordless.config.redirect_back_after_sign_in = false.

Looking up the user

By default Passwordless uses the passwordless_with column to case insensitively fetch the user resource.

You can override this by defining a class method fetch_resource_for_passwordless in your user model. This method will be called with the down-cased, stripped email and should return an ActiveRecord instance.

ruby
class User < ApplicationRecord
  def self.fetch_resource_for_passwordless(email)
    find_or_create_by(email: email)
  end
end

Test helpers

To help with testing, a set of test helpers are provided.

If you are using RSpec, add the following line to your spec/rails_helper.rb:

ruby
require "passwordless/test_helpers"

If you are using TestUnit, add this line to your test/test_helper.rb:

ruby
require "passwordless/test_helpers"

Then in your controller, request, and system tests/specs, you can utilize the following methods:

ruby
passwordless_sign_in(user) # signs you in as a user
passwordless_sign_out # signs out user

Security considerations

There's no reason that this approach should be less secure than the usual username/password combo. In fact this is most often a more secure option, as users don't get to choose the horrible passwords they can't seem to stop using. In a way, this is just the same as having each user go through "Forgot password" on every login.

But be aware that when everyone authenticates via emails, the way you send those mails becomes a weak spot. Email services usually provide a log of all the mails you send so if your email delivery provider account is compromised, every user in the system is as well. (This is the same for "Forgot password".) Reddit was once compromised using this method.

Ideally you should set up your email provider to not log these mails. And be sure to turn on non-SMS 2-factor authentication if your provider supports it.

Alternatives

  • OTP JWT -- Passwordless JSON Web Tokens

License

MIT

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyauthenticationenginepasswordlessrails

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架