设计-api宝石是利用设计宝石 在铁路应用上添加Ruby认证的方便方法. 它为访问符和r提供支持
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
lockable, confirmable, trackable are detected and honored automaticallydocs/ holds contractual architecture, API, and configuration referencesA 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:
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 noteFor the full component map and request lifecycle diagrams, see docs/architecture.md.
| Dependency | Version |
|---|---|
| Ruby | >= 2.7 |
| Rails | >= 6.0 |
| Devise | >= 4.7.2 |
1. Install the gem
bundle add devise-apiOr track main from your Gemfile:
gem 'devise-api', github: 'nejdetkadir/devise-api', branch: 'main'2. Generate the migration and locales
rails generate devise_api:install
rails db:migrateThis 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
curl -X POST http://localhost:3000/users/tokens/sign_up
-H 'Content-Type: application/json'
-d '{ "email": "[email protected]", "password": "123456" }'
curl -X POST http://localhost:3000/users/tokens/refresh
-H 'Authorization: Bearer REFRESH_TOKEN'
curl -X POST http://localhost:3000/users/tokens/revoke
-H 'Authorization: Bearer ACCESS_TOKEN'
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' }
endThe 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 |
# 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# config/initializers/devise.rb
require 'devise/api/responses/token_response_decorator'
Devise::Api::Responses::TokenResponse.prepend Devise::Api::Responses::TokenResponseDecoratorbase_token_model and base_controller are stored as class names and resolved lazily, so you can subclass without load-order problems:
# app/models/api_token.rb
class ApiToken < Devise::Api::Token
belongs_to :organization, optional: true
end# config/initializers/devise.rb
Devise.setup do |config|
config.api.configure do |api|
api.base_token_model = 'ApiToken'
api.base_controller = 'Api::BaseController'
end
endThe before_* / after_successful_* callbacks (see Configuration) are handy for audit logging, analytics, or sending welcome emails:
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.
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:
# 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# 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 promptTests 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.
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.
The gem is available as open source under the terms of the MIT License.
暂无开放 Issues,或尚未同步最近议题。