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

simple_token_authentication

> 后端框架
Open source

Simple (and safe*) token authentication for Rails apps or API with Devise.

1.5K stars0 likes1 views
WebsiteGitHub

About

Simple (and safe*) token authentication for Rails apps or API with Devise.

Simple Token Authentication

Token authentication support has been removed from Devise for security reasons. In this gist, Devise's José Valim explains how token authentication should be performed in order to remain safe (see important warning below).

This gem packages the content of the gist and provides a set of convenient options for increased flexibility.

DISCLAIMER: I am not José Valim, nor has he been involved in the gem bundling process. Implementation errors, if any, are mine; and contributions are welcome. -- GB

Security notice

Security notice: As the name of the gem indicates, it provides a very basic mechanism for token authentication. If your tokens are not discarded after a single use, or you don't know how to mitigate replay attacks, then you should look at alternatives. (Simple Token Authentication doesn't mitigate those attacks for you.)

In other words: if you don't know why Simple Token Authentication is safe to use in your specific use case, then it probably isn't.

So... what does the gem do? Simple Token Authentication allows to generate, revoke, and safely compare tokens for authentication purposes. That's not the only thing you need to implement a safe authentication protocol, but it can be a part of it.

Personal note: I've used the gem to manage single-use sign-in links sent by email (that's what I created it for). I would use it again for that purpose. Please do your research and check carefully if this tool is adequate to your level of experience and threat model. -- GB

Installation

In a nutshell

First install Devise and configure it with any modules you want, then add the gem to your Gemfile and bundle install:

# Gemfile

gem 'simple_token_authentication', '~> 1.0' # see semver.org

Once that done, only two steps are required to setup token authentication:

  1. Make one or more models token authenticatable (ActiveRecord and Mongoid are supported)
  2. Allow controllers to handle token authentication (Rails, Rails API, and ActionController::Metal are supported)

If you want more details about how the gem works, keep reading! We'll get to these two steps after the overview.

Overview

Simple Token Authentication provides the ability to manage an authentication_token from your model instances. A model with that ability enabled is said to be token authenticatable (typically, the User model will be made token authenticatable).

The gem also provides the ability for any controller to handle token authentication for one or multiple token authenticatable models. That ability allows, for example, to automatically sign in an user when the correct credentials are provided with a request. A controller with that ability enabled is said to behave as a token authentication handler. The token authentication credentials for a given request can be provided either in the form of query params, or HTTP headers. By default, the required credentials are the user's email and their authentication token.

What happens when a request is provided with no credentials or incorrect credentials is highly configurable (some scenarios may require access to be denied, other may allow unauthenticated access, or provide others strategies to authenticate users). By default, when token authentication fails, Devise is used as a fallback to ensure a consistent behaviour with controllers that do not handle token authentication.

Make models token authenticatable

ActiveRecord

First define which model or models will be token authenticatable (typ. User):

# app/models/user.rb

class User < ActiveRecord::Base
  acts_as_token_authenticatable

  # Note: you can include any module you want. If available,
  # token authentication will be performed before any other
  # Devise authentication method.
  #
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :invitable, :database_authenticatable,
         :recoverable, :rememberable, :trackable, :validatable,
         :lockable

  # ...
end

If the model or models you chose have no :authentication_token attribute, add them one (with a unique index):

rails g migration add_authentication_token_to_users "authentication_token:string{30}:uniq"
rake db:migrate

Mongoid

Define which model or models will be token authenticatable (typ. User):

# app/models/user.rb

class User
  include Mongoid::Document
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  ## Token Authenticatable
  acts_as_token_authenticatable
  field :authentication_token

  # ...
end

Allow controllers to handle token authentication

Finally define which controllers will handle token authentication (typ. ApplicationController) for which token authenticatable models:

…

Configuration

Some aspects of the behavior of Simple Token Authentication can be customized with an initializer.

The file below contains examples of the patterns that token authentication handlers will watch for credentials (e.g. user_email, X-SuperAdmin-Token) and how to customize them:

…

Usage

Tokens Generation

Assuming user is an instance of User, which is token authenticatable: each time user will be saved, and user.authentication_token.blank? it receives a new and unique authentication token (via Devise.friendly_token).

Token Request

Simple Token Authentication only provides the functionality to authenticate a user based on their authentication_token. For example how to setup your controller to get the token at first please check this wiki

Authentication Method 1: Query Params

You can authenticate passing the user_email and user_token params as query params:

GET https://[email protected]&user_token=1G8_s7P-V-4MGojaKD7a

The token authentication handler (e.g. ApplicationController) will perform the user sign in if both are correct.

Authentication Method 2: Request Headers

You can also use request headers (which may be simpler when authenticating against an API):

X-User-Email [email protected]
X-User-Token 1G8_s7P-V-4MGojaKD7a

In fact, you can mix both methods and provide the user_email with one and the user_token with the other, even if it would be a freak thing to do.

Integration with other authentication and authorization methods

If sign-in is successful, no other authentication method will be run, but if it doesn't (the authentication params were missing, or incorrect) then Devise takes control and tries to authenticate_user! with its own modules. That behaviour can however be modified for any controller through the fallback option (which defaults to fallback: :devise).

When fallback: :exception is set, then an exception is raised on token authentication failure. The resulting controller behaviour is very similar to the behaviour induced by using the Devise authenticate_user! callback instead of authenticate_user. That setting allows, for example, to prevent unauthenticated users to accede API controllers while disabling the default fallback to Devise.

Important: Please do notice that controller actions without CSRF protection must disable the Devise fallback for security reasons (both fallback: :exception and fallback: :none will disable the Devise fallback). Since Rails enables CSRF protection by default, this configuration requirement should only affect controllers where you have disabled it specifically, which may be the case of API controllers.

To use no fallback when token authentication fails, set fallback: :none.

Hooks

One hook is currently available to trigger custom behaviour after an user has been successfully authenticated through token authentication. To use it, implement or mixin a module with an after_successful_token_authentication method that will be ran after authentication from a token authentication handler:

# app/controller/application_controller.rb

class ApplicationController < ActiveController::Base
  acts_as_token_authentication_handler_for User

  # ...

  private

    def after_successful_token_authentication
      # Make the authentication token to be disposable - for example
      renew_authentication_token!
    end
end

Testing

Here is an example of how you can test-drive your configuration using Minitest:

class SomeControllerTest < ActionController::TestCase

  test "index with token authentication via query params" do
    get :index, { user_email: "[email protected]", user_token: "1G8_s7P-V-4MGojaKD7a" }
    assert_response :success
  end

  test "index with token authentication via request headers" do
    @request.headers['X-User-Email'] = "[email protected]"
    @request.headers['X-User-Token'] = "1G8_s7P-V-4MGojaKD7a"

    get :index
    assert_response :success
  end
end

Documentation

Frequently Asked Questions

Any question? Please don't hesitate to open a new issue to get help. I keep questions tagged to make possible to review the open questions, while closed questions are organized as a sort of FAQ.

Change Log

Releases are commented to provide a brief change log, details can be found in the CHANGELOG file.

Development

Testing and documentation

This gem development has been test-driven since v1.0.0. Until v1.5.1, the gem behaviour was described using [Cucumber][cucumber] and [RSpec][rspec] in a dummy app generated by [Aruba][aruba]. Since v1.5.2 it is described using Rspec alone and [Appraisal][appraisal] is used since v1.13.0 for [regression testing][regression].

RSpec [tags][tags] are used to categorize the spec examples.

Spec examples that are tagged as public describe aspects of the gem public API, and MAY be considered as the gem documentation.

The private or protected specs are written for development purpose only. Because they describe internal behaviour which may change at any moment without notice, they a

GitHub Issues· 81 open

View all on GitHub
  • #406

    Is there an ETA on a release?

    Updated Apr 29, 2025
  • #309

    "error":"You need to sign in or sign up before continuing."

    support requestUpdated Jan 8, 2024
  • #390

    Can we use JWT as a user token?

    Updated Dec 27, 2021
  • #360

    Q: How to do not require user_email?

    support requestUpdated Apr 17, 2021
  • #370

    Identify support requests, feature requests in issues and pull requests

    communityUpdated Jan 3, 2021
  • #293

    Documentation to handle devise sign_in

    documentation requestsupport requestUpdated Jan 2, 2021
  • #26

    Configurable option to reset token upon password change

    bugsecurityfeature requestUpdated Jan 2, 2021
  • #15

    Given some external support, the gem should be able to ensure (optionally) that generated tokens never repeat

    enhancementsecurityfeature requestUpdated Jan 2, 2021
  • #296

    Signed requests

    support requestUpdated Jan 2, 2021
  • #315

    Q: Support for Cassandra with cequel?

    feature requestUpdated Jan 2, 2021

Highlights

  • •Ruby
  • •api
  • •authentication
  • •devise
  • •mongoid

> Tags

Rubyapiauthenticationdevisemongoid

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 生态主流微服务框架