---
title: "Rails 8的Authentication模块"
url: "https://versun.me/rails-8-authentication-module"
markdown_url: "https://versun.me/rails-8-authentication-module.md"
format: "note"
published: "2024-10-11T07:55:39.000Z"
updated: "2026-01-05T05:29:52.000Z"
collections:
  - "Blog"
site: "Versun"
---

# Rails 8的Authentication模块

如果你像我一样刚开始学习Rails，则建议直接开始使用Rails 8.0.0.beta版本，因为该[版本更新优化了很多功能](https://rubyonrails.org/2024/9/27/rails-8-beta1-no-paas-required)，最重要的是加入了身份验证模块抽象层，不用像7之前的版本那样麻烦。  
在这里记录下我的相关笔记

- 一键生成身份验证系统： `bin/rails generate authentication`  
该命令会创建User、Current、Session三个模型，并且会在`app/controllers/conerns`下添加Authentication模块
- 只有认证模块，没有注册模块
- 默认使用邮箱和密码进行认证
- Authentication模块的方法，建议直接打开该模块文件，就55行代码，非常的简洁明了
- 查看三个模型对应的的controller文件，也非常简洁明了。。。
- 认证流程([via](https://www.bigbinary.com/blog/rails-8-introduces-a-basic-authentication-generator))：  
![1858501620801126776-Gcq5LQfXcAA-_U3.jpg](https://media.jant.me/media/sit_01krgk4fnyf24sfk8an30re4xv/files/med_01m94nzbkgexy9h5pj8f0zfxr0.jpg)
- 重置密码流程([via](https://www.bigbinary.com/blog/rails-8-introduces-a-basic-authentication-generator))：  
![1857239379875606782-GcY9JH3akAA1Lm6.png](https://media.jant.me/media/sit_01krgk4fnyf24sfk8an30re4xv/files/med_01m94nzd8xe1ntjvep105zp1d2.png)
- 添加注册流程
  1. 创建Users Controller: `bin/rails g controller Users`
     ```
     # File: app/controllers/users_controller.rb
     class UsersController < ApplicationController
     allow_unauthenticated_access only: %i[ new create ]
     def new
     end
     
     def create
     @user = User.new(user_params)
     if @user.save
       redirect_to root_path, notice: "User was successfully created."
     else
       render :new
     end
     end
     
     private
     def user_params
     params.require(:user).permit(:email_address, :password, :password_confirmation)
     end
     end
     ```
  2. 创建view文件
  
     &lt;pre&gt;&lt;code&gt;#File: app/views/users/new.html.erb
     &amp;lt;%= tag.div(flash\[:alert\], style: &amp;#34;color:red&amp;#34;) if flash\[:alert\] %&amp;gt;
     &amp;lt;%= tag.div(flash\[:notice\], style: &amp;#34;color:green&amp;#34;) if flash\[:notice\] %&amp;gt;
     &lt;strong&gt;Sign Up&lt;/strong&gt;  
     
     &amp;lt;%= form\_with(model:User) do |form| %&amp;gt;
     &amp;lt;%= form.email\_field :email\_address, required: true, autofocus: true, autocomplete: &amp;#34;username&amp;#34;, placeholder: &amp;#34;Enter your email address&amp;#34;, value: params\[:email\_address\] %&amp;gt;  
     
     &amp;lt;%= form.password\_field :password, required: true, placeholder: &amp;#34;Enter your password&amp;#34;, maxlength: 72 %&amp;gt;  
     
     &amp;lt;%= form.password\_field :password\_confirmation, required: true, placeholder: &amp;#34;Confirm your password&amp;#34;, maxlength: 72 %&amp;gt;  
     
     &amp;lt;%= form.submit &amp;#34;Sign up&amp;#34; %&amp;gt;
     &amp;lt;% end %&amp;gt;&lt;/code&gt;&lt;/pre&gt;
  3. 添加route
     ```
     #File: config/routes.rb
     resources :users
     ```
