百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
D

devise-api

> 后端框架
开源

设计-api宝石是利用设计宝石 在铁路应用上添加Ruby认证的方便方法. 它为访问符和r提供支持

176 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

设计-api宝石是利用设计宝石 在铁路应用上添加Ruby认证的方便方法. 它为访问符和r提供支持

devise-api

Token-based API authentication for Devise. Opaque access + refresh tokens, one devise :api module, zero Warden strategies to write.

devise-api is a Rails engine that plugs into Devise's own extension mechanism. Add :api to your Devise model and you get sign-up, sign-in, token refresh, revocation, and an authenticated info endpoint — plus controller helpers (authenticate_devise_api_token!, current_devise_api_user) for protecting the rest of your API.

Highlights

  • Opaque access + refresh tokens stored in your database — revocable at any time, no JWT invalidation headaches
  • Refresh token rotation with reuse detection (a replayed rotated token revokes the whole token family)
  • Plays well with Devise modules — lockable, confirmable, trackable are detected and honored automatically
  • ⚙️ Fully configurable — token TTLs and generators, paranoid mode, header/params extraction, per-action callbacks, and swappable base classes for the token model and controller
  • Service objects built on dry-monads — every endpoint delegates to a composable, overridable service
  • Documented for humans and AI agents — docs/ holds contractual architecture, API, and configuration references

Table of contents

  • How it works
  • Requirements
  • Quick start
  • Endpoints
  • Protecting your own endpoints
  • Response payloads
  • Configuration
  • Security checklist
  • Devise module compatibility
  • Customization
  • Documentation
  • Development
  • Contributing
  • License

How it works

A client signs in once, then uses a short-lived access token per request and a longer-lived refresh token to get new access tokens without re-sending credentials:

…

Tokens are opaque random strings (Devise.friendly_token by default) persisted in a devise_api_tokens table with a polymorphic resource_owner, so one table serves any number of Devise scopes (User, Customer, …). A token is active only while it is neither expired nor revoked:

mermaid
stateDiagram-v2
    [*] --> Active: sign_up / sign_in / refresh
    Active --> Expired: access_token.expires_in elapses
    Active --> Revoked: POST /tokens/revoke
    Active --> Revoked: rotation on refresh
    Expired --> [*]: refresh (mints a new pair)
    Revoked --> [*]
    note right of Revoked
        Reuse detection: presenting a rotated
        refresh token again revokes the
        entire token family
    end note

For the full component map and request lifecycle diagrams, see docs/architecture.md.

Requirements

Dependency Version
Ruby >= 2.7
Rails >= 6.0
Devise >= 4.7.2

Quick start

1. Install the gem

bash
bundle add devise-api

Or track main from your Gemfile:

ruby
gem 'devise-api', github: 'nejdetkadir/devise-api', branch: 'main'

2. Generate the migration and locales

bash
rails generate devise_api:install
rails db:migrate

This copies a migration for the devise_api_tokens table and the locale file config/locales/devise_api.en.yml into your app.

3. Add the :api module to your Devise model

…

bash

Sign up

curl -X POST http://localhost:3000/users/tokens/sign_up
-H 'Content-Type: application/json'
-d '{ "email": "[email protected]", "password": "123456" }'

Refresh (note: the REFRESH token goes in the Authorization header)

curl -X POST http://localhost:3000/users/tokens/refresh
-H 'Authorization: Bearer REFRESH_TOKEN'

Revoke

curl -X POST http://localhost:3000/users/tokens/revoke
-H 'Authorization: Bearer ACCESS_TOKEN'

Info

curl http://localhost:3000/users/tokens/info
-H 'Authorization: Bearer ACCESS_TOKEN'


Route paths and the controller are customizable through the standard `devise_for` options:

```ruby
# config/routes.rb
Rails.application.routes.draw do
  devise_for :customers, controllers: { tokens: 'customers/api/tokens' }
end

Protecting your own endpoints

The gem mixes three helpers into every controller:

Helper Returns
authenticate_devise_api_token! Renders a 401 error response unless a valid, active access token is presented
current_devise_api_token The active Devise::Api::Token (or nil)
current_devise_api_user The token's resource owner (or nil) — works for any scope, despite the name
ruby
# app/controllers/api/v1/orders_controller.rb
class Api::V1::OrdersController (_resource_owner) { false }
    api.access_token.generator = ->(_resource_owner) { Devise.friendly_token(60) }

    # Refresh token
    api.refresh_token.enabled = true
    api.refresh_token.expires_in = 1.week
    api.refresh_token.expires_in_infinite = ->(_resource_owner) { false }
    api.refresh_token.generator = ->(_resource_owner) { Devise.friendly_token(60) }
    api.refresh_token.rotation_enabled = false # recommended: true (see Security checklist)

    # Sign up
    api.sign_up.enabled = true
    api.sign_up.extra_fields = [] # e.g. %i[first_name last_name] — writable at sign-up AND echoed in responses

    # Error responses
    api.error_response.verbose_account_state = true # false hides lockable/confirmable details from errors
    api.paranoid = false # true makes unknown accounts indistinguishable from wrong passwords

    # Token extraction
    api.authorization.key = 'Authorization'
    api.authorization.scheme = 'Bearer'
    api.authorization.location = :both # :header, :params, or :both (params win)
    api.authorization.params_key = 'access_token'

    # Base classes (string names, constantized lazily — point at your own subclasses)
    api.base_token_model = 'Devise::Api::Token'
    api.base_controller = '::DeviseController'

    # Lifecycle hooks (all default to no-ops)
    api.before_sign_in  = ->(params, request, resource_class) {}
    api.before_sign_up  = ->(params, request, resource_class) {}
    api.before_refresh  = ->(token, request) {}
    api.before_revoke   = ->(token, request) {}
    api.after_successful_sign_in = ->(resource_owner, token, request) {}
    api.after_successful_sign_up = ->(resource_owner, token, request) {}
    api.after_successful_refresh = ->(resource_owner, token, request) {}
    api.after_successful_revoke  = ->(resource_owner, token, request) {}
  end
end

…

ruby
# app/lib/devise/api/responses/token_response_decorator.rb
module Devise::Api::Responses::TokenResponseDecorator
  def body
    default_body.merge({ roles: resource_owner.roles })
  end
end
ruby
# config/initializers/devise.rb
require 'devise/api/responses/token_response_decorator'

Devise::Api::Responses::TokenResponse.prepend Devise::Api::Responses::TokenResponseDecorator

Swap the base classes

base_token_model and base_controller are stored as class names and resolved lazily, so you can subclass without load-order problems:

ruby
# app/models/api_token.rb
class ApiToken < Devise::Api::Token
  belongs_to :organization, optional: true
end
ruby
# config/initializers/devise.rb
Devise.setup do |config|
  config.api.configure do |api|
    api.base_token_model = 'ApiToken'
    api.base_controller = 'Api::BaseController'
  end
end

Hook into the lifecycle

The before_* / after_successful_* callbacks (see Configuration) are handy for audit logging, analytics, or sending welcome emails:

ruby
api.after_successful_sign_up = lambda { |resource_owner, _token, _request|
  WelcomeMailer.with(user: resource_owner).welcome.deliver_later
}

before_* return values are ignored — raise, or use a before_action in a subclassed controller, if you need to halt a request.

Build your own services

Every endpoint delegates to a service object built on dry-monads, dry-types, and dry-initializer. Inherit from Devise::Api::BaseService to compose your own:

ruby
# app/services/devise/api/tokens_service/v2/create.rb
module Devise::Api::TokensService::V2
  class Create < Devise::Api::BaseService
    option :params, type: Types::Hash, reader: true
    option :resource_class, type: Types::Class, reader: true

    def call
      # ...
      Success(resource)
    end
  end
end
ruby
# app/controllers/api/v1/tokens_controller.rb
def create
  result = Devise::Api::TokensService::V2::Create.new(params: params, resource_class: Customer).call

  if result.success?
    render json: result.success, status: :created
  else
    render json: result.failure, status: :unprocessable_entity
  end
end

…

bash
bin/setup                # install dependencies
bundle exec rake         # what CI runs: RSpec + RuboCop
bundle exec rake rspec   # tests only
bin/console              # interactive prompt

Tests run against the dummy Rails app in spec/dummy. To install the gem locally run bundle exec rake install; to release, bump version.rb and run bundle exec rake release.

Contributing

Bug reports and pull requests are welcome on GitHub. Please read docs/README.md for the ground rules (docs are contractual — behavior changes must update the matching document) and check the known-issues backlog before "fixing" surprising code.

This project is intended to be a safe, welcoming space for collaboration; contributors are expected to follow the code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Issues· 3 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubydevisedevise-apidevise-api-authenticatabledevise-gem-extension

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类后端框架
定价开源

> 相关工具

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