用途
该技能用于在 Rails 8 应用中实现认证功能。Rails 8 内置了认证生成器,可创建完整、安全的认证系统,无需依赖外部 gem。适用于设置用户认证、登录/登出、会话管理、密码重置流程等场景。
主要能力
通过运行 bin/rails generate authentication 生成认证代码,再执行 bin/rails db:migrate 运行迁移。生成的结构包括:
- 模型:
user.rb(带 has_secure_password)、session.rb(会话跟踪)、current.rb(Current.user 访问器) - 控制器:
sessions_controller.rb(登录/登出)、passwords_controller.rb(密码重置)、concerns/authentication.rb(认证辅助方法) - 视图:
sessions/new.html.erb(登录表单)、passwords/new.html.erb(忘记密码)、passwords/edit.html.erb(重置密码)
核心组件包括:
- User 模型:使用 has_secure_password,关联 sessions,对 email_address 做规范化与校验(存在性、唯一性、邮箱格式)。
- Session 模型:属于 user,创建前生成 token(SecureRandom.urlsafe_base64(32)),提供 find_by_token 方法。
- Current 模型:继承 ActiveSupport::CurrentAttributes,持有 session 属性并委托 user。
- Authentication concern:包含 require_authentication 前置动作、authenticated? 辅助方法、allow_unauthenticated_access 类方法,以及 resume_session、request_authentication、start_new_session_for、terminate_session 等方法。
使用方式
在 ApplicationController 中包含 Authentication 后,默认所有动作都需要认证。可通过 allow_unauthenticated_access only: [:index, :about] 允许特定动作公开访问。
访问当前用户:控制器中使用 Current.user、Current.user.email_address;视图中使用 <%= Current.user.email_address %>;模型中谨慎使用 Current.user。
登录流程:SessionsController 中 allow_unauthenticated_access only: [:new, :create],create 动作使用 User.authenticate_by 验证凭据,成功则调用 start_new_session_for 并重定向,失败则渲染 new 并返回 unprocessable_entity。destroy 动作调用 terminate_session 并重定向。
测试:提供请求规格示例(验证登录成功/失败、登出),以及测试辅助模块 AuthenticationHelpers(sign_in/sign_out),可包含到 request 和 system 类型测试中。还提供受保护路由的规格示例。
常见自定义:
- 记住我:在 start_new_session_for 中增加 remember 参数,设置 cookie 过期时间为 2 周后。
- 多会话跟踪:User 模型中定义 active_sessions(30 天内创建的会话)和 terminate_all_sessions_except(current_session)。
- 速率限制:在 SessionsController 中对 create 动作使用
rate_limit to: 10, within: 3.minutes,超限时重定向并提示。
适用场景
适用于基于 Rails 8 构建、需要用户认证、会话管理、密码重置等功能的 Web 应用。
限制
资料未提供关于收费、价格、平台支持范围、性能效果等方面的信息,暂未提供。