【山竹记账后端】10.后端如何实现 JWT


大纲链接 §

[toc]


1. 给登录写测试用例 ⇧

  • 需要实现config/routes.rb中路由 resource :session, only: [ :create, :destroy ]
  • 请求登录建立会话 Post /api/v1/session 注意和路由路径一致
  • 请特别注意单复数
    • resource :session, only: [:create, :destroy] 一个登录会话使用单数
    • resource :me, only: [:show] 单个用户信息使用单数

创建对应 Controller ⇧

  • 运行命令 bin/rails g controller api/v1/sessions_controller

    1
    2
    3
    
      create  app/controllers/api/v1/sessions_controller.rb
      invoke  rspec
      create    spec/requests/api/v1/sessions_spec.rb
  • 这里的 sessions_controller 有复数

  • 自动创建一个对应的测试用例文件 spec/requests/api/v1/sessions_spec.rb

  • 需要在 app/controllers/api/v1/sessions_controller.rb 实现一个 create 方法

spec/requests/api/v1/sessions_spec.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
require 'rails_helper'

RSpec.describe "Api::V1::Sessions", type: :request do
  describe "登录会话" do
    it "可以登录(创建会话)" do
      post '/api/v1/session',
        params: { email: 'xxx@163.com', code: '123456' }
      expect(response).to have_http_status(200)
      # 解析 response body
      json = JSON.parse response.body
      expect(json["jwt"]).to be_a_(String)
    end
  end
end
  • 可以在测试环境中写死验证码 code = Rails.env.test? ? "123456" : params[:code]

app/controllers/api/v1/sessions_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Api::V1::SessionsController < ApplicationController
  def create
    # 如果是测试环境 code就永远为 123456
    if Rails.env.test?
      # 直接认为验证码必须为 123456
    else
      # 使用传给我的验证码
    end
  end
end

2. 实现登录接口 ⇧

思路

  • 只要满足以下两个条件,就可确认是收到验证码了
    • 确实发送过了验证码 email, code
    • 发送的 code 没有被使用过,确保用户是第一个使用这个验证码的人,即该表中 used_at 字段为空
  • 满足以上条件就说明当前用户确实收到了发送的验证码,并且是首次使用的验证码
  • 查找数据库中是否有符合 email, code 并且 code 的 used_at: nil 为空的数据

app/controllers/api/v1/sessions_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Api::V1::SessionsController < ApplicationController
  def create
    canSignIn = ValidationCode.exists? email: params[:email],
      code: params[:code], used_at: nil
    if !canSignIn
      # render status: 401, json: { errors: "邮箱或验证码错误" }
      render status: :unauthorized, json: { errors: "邮箱或验证码错误" }
      return
    end
    user = User.find_by_email params[:email]
    if user.nil?
      # render status: 404, json: { errors: "用户不存在" }
      render status: :not_found, json: { errors: "用户不存在" }
    else
      # render status: 200, json: {
      render status: :ok, json: {
        jwt: "xxxxxxxxxx"
        # JWT.encode({
        #   user_id: user.id,
        #   email: user.email
        # }, Rails.application.credentials.secret_key_base)
      }
    end
  end
end
  • 可简化 return render status: :unauthorized, json: { errors: "邮箱或验证码错误" } if !canSignIn
  • 可简化 return render status: :unauthorized, json: { errors: "xxx" } if not canSignIn
  • 可简化 return render status: :unauthorized, json: { errors: "xxx" } unless canSignIn
  • 这里的返回的jwt暂时先写死,后面再去引入JWT库,变成真正的uid密文

测试环境是否可以不发送验证码,直接点击提交?

  • 可以添加测试环境的分支逻辑 Rails.env.test?

app/controllers/api/v1/sessions_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Api::V1::SessionsController < ApplicationController
  def create
    # 如果是测试环境,则跳过验证码查找
    if Rails.env.test?
      return render status: :unauthorized if params[:code] != "123456"
    else
      canSignIn = ValidationCode.exists? email: params[:email],
        code: params[:code], used_at: nil
      return render status: :unauthorized, json: { errors: "邮箱或验证码错误" } unless canSignIn
    end
    user = User.find_by email: params[:email]
    print user
    if user.nil?
      render status: :not_found, json: { errors: "用户不存在" }
    else
      render status: :ok, json: { jwt: "xxxxxxxxxx" }
    end
  end
end
  • 现在运行 rspec 结果还是未通过,原因是测试环境中目前服务器数据库并没有用户邮箱的数据,所以无法找到,返回404
  • 可以在测试用例中直接创建用户邮箱数据

spec/requests/api/v1/sessions_spec.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
require 'rails_helper'

RSpec.describe "Api::V1::Sessions", type: :request do
  describe "登录会话" do
    it "可以登录(创建会话)" do
      User.create email: 'xxx@163.com'
      post '/api/v1/session',
        params: { email: 'xxx@163.com', code: '123456' }
      expect(response).to have_http_status(200)
      json = JSON.parse response.body
      expect(json["jwt"]).to be_a(String)
    end
  end
end
  • 使用Rails提供的方法创建数据 User.create email: 'xxx@163.com',测试用例后会自动删除

3. 实现 JWT encode ⇧

安装jwt和调试 ⇧

搜索 jwt rails

修改 Gemfile

1
gem 'jwt'
  • 运行 bundle install

app/controllers/api/v1/sessions_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
require 'jwt'
class Api::V1::SessionsController < ApplicationController
  def create
    # 如果是测试环境,则跳过验证码查找
    if Rails.env.test?
      return render status: :unauthorized, json: { errors: "邮箱或验证码错误" } if
        params[:code] != "123456"
    else
      canSignIn = ValidationCode.exists? email: params[:email],
        code: params[:code], used_at: nil
      return render status: :unauthorized, json: { errors: "邮箱或验证码错误" } unless canSignIn
    end
    user = User.find_by_email params[:email]
    if user.nil?
      render status: :not_found, json: { errors: "用户不存在" }
    else
      # JWT.encode({})
      payload = { user_id: user.id }
      token = JWT.encode payload, nil, 'none'
      render status: :ok, json: { jwt: token }
    end
  end
end
  • 使用 JWT.encode({}),暂时先转换算法为空,仅传参 payload

在测试用例中打印 spec/requests/api/v1/sessions_spec.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
require 'rails_helper'

RSpec.describe "Api::V1::Sessions", type: :request do
  describe "登录会话" do
    it "可以登录(创建会话)" do
      User.create email: 'xmasuhai@163.com'
      post '/api/v1/session',
        params: { email: 'xmasuhai@163.com', code: '123456' }
      expect(response).to have_http_status(200)
      json = JSON.parse response.body

      decoded_token = JWT.decode(json["jwt"], nil, true, { algorithm: 'none' })
      p("jwt_______________________")
      p json["jwt"]
      jwt_parts = json["jwt"].split(".")
      p jwt_parts
      p decoded_token
      p("_______________________jwt")
      expect(json["jwt"]).to be_a(String)
    end
  end
end
  • 运行 rspec,查看结果:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    ..."jwt_______________________"
    "eyJhbGciOiJub25lIn0.eyJ1c2VyX2lkIjo0OH0."
    ["eyJhbGciOiJub25lIn0", "eyJ1c2VyX2lkIjo0OH0"]
    [{"user_id"=>48}, {"alg"=>"none"}]
    "_______________________jwt"
    .....
    
    Finished in 0.09642 seconds (files took 0.50493 seconds to load)
    8 examples, 0 failures
  • 也可以将两部分 JWT 字符串分别在浏览器控制台中,使用 window.atob() 解码打印查看


添加加密算法 ⇧

app/controllers/api/v1/sessions_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
require 'jwt'
class Api::V1::SessionsController < ApplicationController
  def create
    # 如果是测试环境,则跳过验证码查找
    if Rails.env.test?
      return render status: :unauthorized, json: { errors: "邮箱或验证码错误" } if
        params[:code] != "123456"
    else
      canSignIn = ValidationCode.exists? email: params[:email],
        code: params[:code], used_at: nil
      return render status: :unauthorized, json: { errors: "邮箱或验证码错误" } unless canSignIn
    end
    user = User.find_by_email params[:email]
    if user.nil?
      render status: :not_found, json: { errors: "用户不存在" }
    else
      payload = { user_id: user.id }
      hmac_secret = 'my$ecretK3y'
      token = JWT.encode(payload, hmac_secret, 'HS256')
      render status: :ok, json: { jwt: token }
    end
  end
end
  • 加盐 hmac_secret = 'my$ecretK3y'
  • 添加加密算法和加盐算出的密钥 token = JWT.encode(payload, hmac_secret, 'HS256')

同时修改测试用例 spec/requests/api/v1/sessions_spec.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
require 'rails_helper'

RSpec.describe "Api::V1::Sessions", type: :request do
  describe "登录会话" do
    it "可以登录(创建会话)" do
      User.create email: 'xmasuhai@163.com'
      post '/api/v1/session',
        params: { email: 'xmasuhai@163.com', code: '123456' }
      expect(response).to have_http_status(200)
      json = JSON.parse response.body
      decoded_token = JWT.decode json["jwt"],
        "my$ecretK3y", true, { algorithm: 'HS256' }
      p("jwt_______________________")
      p json["jwt"]
      jwt_parts = json["jwt"].split(".")
      p jwt_parts
      p decoded_token
      p("_______________________jwt")
      expect(json["jwt"]).to be_a(String)
    end
  end
end
  • 解码时也需要用的加盐字符串和算法:
    • JWT.decode json["jwt"], "my$ecretK3y", true, { algorithm: 'HS256' }
  • 此时再运行 rspec,查看结果:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    ..."jwt_______________________"
    "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1NH0.CEq5He5Nf9N4ULQXKdh16gOE07av-9cKd-EyJ4Ax7PU"
    ["eyJhbGciOiJIUzI1NiJ9", "eyJ1c2VyX2lkIjo1NH0", "CEq5He5Nf9N4ULQXKdh16gOE07av-9cKd-EyJ4Ax7PU"]
    [{"user_id"=>54}, {"alg"=>"HS256"}]
    "_______________________jwt"
    .....
    
    Finished in 0.13003 seconds (files took 0.92865 seconds to load)
    8 examples, 0 failures

永远不要将密钥(加盐)写在代码里面 ⇧

  • 终端输入 edit 按下⬆️ 键,搜索到历史命令 EDITOR="code --wait" rails credentials:edit(旧版)
  • 新版可以运行 VISUAL="code --wait" rails credentials:edit
  • 会弹出一个 code 窗口,将密钥写入 config/credentials/development.key 文件中
  • 添加一行 jwt_secret: ENV['JWT_SECRET'],可使用 uuid Generator 来生成

编辑临时文件后,保存并关闭 /tmp/2026xxxx-76205-xq5wph-credentials.yml

1
2
3
4
5
6
7
8
# aws:
#   access_key_id: 123
#   secret_access_key: 345

# Used as the base secret for all MessageVerifiers in Rails,
# including the one protecting cookies.
email_password: wydxcuzzskjebehe
secret_key_base: 485fwe8b-4f34-4e3f9-93ff-55d34rt8ef97d2

可以看见到终端信息提示保存成功

1
2
Editing config/credentials.yml.enc...
File encrypted and saved.
  • 加密内容详见 【山竹记账后端】5.密钥管理

4. 给当前用户接口写测试用例 ⇧

  • 获取当前用户信息的接口 resource :me, only: [ :show ] 来做解密
  • 成功找到当前用户说明可以成功解密 jwt
  • 创建Controller命令 bin/rails g controller api/v1/mes
    • 或者 bin/rails g controller api/v1/mes_controller
  • 生成以下提示

    1
    2
    3
    
      create  app/controllers/api/v1/mes_controller.rb
      invoke  rspec
      create    spec/requests/api/v1/mes_spec.rb

测试用例 spec/requests/api/v1/mes_spec.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
require 'rails_helper'

RSpec.describe "Api::V1::Mes", type: :request do
  describe "获取当前用户" do
    it "登录后成功获取" do
      user = User.create email: 'xmasuhai@163.com'
      post '/api/v1/session',
        params: { email: 'xmasuhai@163.com', code: '123456' }
      json = JSON.parse response.body
      jwtString = json["jwt"]
      expect(jwtString).to be_a(String)
      headers = {
        "Authorization" => "Bearer #{jwtString}",
        "Accept" => "application/json"
      }
      get '/api/v1/me', headers: headers
      expect(response).to have_http_status(:ok)
      json = JSON.parse response.body
      resource = json["resource"]
      expect(resource["email"]).to eq "xmasuhai@163.com"
      expect(resource["id"]).to eq user.id
    end
  end
end
  • 需要创建测试用例的用户数据
  • 需要先登录,才可以获取用户
  • 发送请求 get '/api/v1/me' 模拟前端传参 jwt

app/controllers/api/v1/mes_controller.rb

  • 暂时先设置占位方法 show

    1
    2
    3
    4
    5
    
    class Api::V1::MesController < ApplicationController
    def show
    head 500
    end
    end
  • 运行 rspec忙着需实现这个控制器方法即可

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    ...F"jwt_______________________"
    "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo2OX0.p8s8_nCTLbYSuaLXST4d_brWCZfPvmdkH39lov5MRY8"
    ["eyJhbGciOiJIUzI1NiJ9", "eyJ1c2VyX2lkIjo2OX0", "p8s8_nCTLbYSuaLXST4d_brWCZfPvmdkH39lov5MRY8"]
    [{"user_id"=>69}, {"alg"=>"HS256"}]
    "_______________________jwt"
    .....
    
    Failures:
    
    1) Api::V1::Mes 获取当前用户 登录后成功获取
     Failure/Error: expect(response).to have_http_status(:ok)
       expected the response to have status code :ok (200) but it was :internal_server_error (500)
     # ./spec/requests/api/v1/me_spec.rb:17:in `block (3 levels) in <main>'
    
    Finished in 0.13996 seconds (files took 0.61865 seconds to load)
    9 examples, 1 failure
    
    Failed examples:
    
    rspec ./spec/requests/api/v1/me_spec.rb:5 # Api::V1::Mes 获取当前用户 登录后成功获取

参考


5. 实现 JWT decode ⇧

  • 如何让方法 show 成功获取当前用户
  • 需要知道是哪个用户,获取用户 user_id
  • 如何获取用户 user_id,需要获取 jwt
  • 需要从 header 中拿到 jwt

app/controllers/api/v1/mes_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Api::V1::MesController < ApplicationController
  # 获取当前用户
  def show
    # get jwt from header
    authorization = request.headers["Authorization"]
    # 去除Bearer
    jwt = authorization.split(" ")[1]
    # decode jwt
    payload = JWT.decode jwt,
      Rails.application.credentials.hmac_secret, true, { algorithm: "HS256" }
    user_id = payload[0]["user_id"]
    currentUser = User.find user_id
    p("show jwt_______________________")
    p "authorization"
    p authorization
    p "jwt"
    p jwt
    p "payload"
    p payload
    p "user_id"
    p user_id
    p "currentUser"
    p currentUser
    p("_______________________show jwt")
    render json: { resource: currentUser }
  end
end
  • 首先获取header中的完整的jwt字段 authorization = request.headers["Authorization"]
  • 获取去除Bearer后的jwt字段 jwt = authorization.split(" ")[1]
  • 解码出payload:JWT.decode jwt, Rails.application.credentials.hmac_secret, true, { algorithm: "HS256" }
  • 根据文档,获取 payload 中的 user_id
  • 找到对应的 currentUser
  • 返回当前用户 render json: { resource: currentUser }

6. try/catch与判空 ⇧

目前代码存在的问题

  • 主要就是代码中有未处理的异常
    • 比如 jwt 解码失败,或者 user_id 为空,或者 currentUser 为空
    • 每一步都需要考虑判空错误处理
  • 可使用 rescue 处理

app/controllers/api/v1/mes_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Api::V1::MesController < ApplicationController
  # 获取当前用户
  def show
    # get jwt from header
    authorization = request.headers["Authorization"]
    # 去除Bearer
    jwt = authorization.split(" ")[1] rescue ""
    # decode jwt
    payload = JWT.decode jwt,
      Rails.application.credentials.hmac_secret,
      true, { algorithm: "HS256" } rescue nil
    if payload.nil?
      render status: :unauthorized, json: { errors: "Invalid JWT" }
      return
    end
    user_id = payload[0]["user_id"] rescue nil
    currentUser = User.find user_id
    if currentUser.nil?
      render status: :unauthorized, json: { errors: "Invalid JWT" }
      return
    end
    render json: { resource: currentUser }
  end
end
  • 需要考虑动态语言 Ruby 每处为空的情况
  • 需要将所有可能为空的情况写测试覆盖
  • 类型是一种小规模的单元测试

优化 app/controllers/api/v1/mes_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Api::V1::MesController < ApplicationController
  # 获取当前用户
  # @raise [StandardError]
  # @return [String] jwt
  # @return [String] errors
  # @return [Integer] status
  def show
    # get jwt from header
    authorization = request.headers["Authorization"]
    # 去除Bearer
    jwt = authorization.split(" ")[1] rescue ""
    # decode jwt
    payload = JWT.decode jwt, Rails.application.credentials.hmac_secret, true, { algorithm: "HS256" } rescue nil
    return render status: :unauthorized, json: { errors: "Invalid JWT" } if payload.nil?
    user_id = payload[0]["user_id"] rescue nil
    currentUser = User.find user_id
    return render status: :unauthorized, json: { errors: "Invalid JWT" } if currentUser.nil?
    render json: { resource: currentUser }
  end
end

7. Rails 路由与控制器单复数规则 ⇧

本项目是 Rails 7.2、config.api_only = true 的 API 项目,测试用 RSpec。 在编写或修改路由、控制器、生成器命令时,请遵守以下规则。

核心原则

  • 控制器类名一律用复数:SessionsController、ValidationCodesController。
  • 用 resources 还是 resource,取决于资源是否需要 :id 来区分个体。
  • 模型类名用单数(ValidationCode),对应的表名是复数(validation_codes)。

路由:resources(复数资源)

用于有很多个、需要用 :id 区分的资源,例如 resources :items。

请求 路径 控制器#动作
GET /items items#index
POST /items items#create
GET /items/:id items#show
PATCH/PUT /items/:id items#update
DELETE /items/:id items#destroy
  • 路径和控制器名都直接使用你写的名字,不做单复数转换。
  • 所以名字必须写复数:resources :items、resources :validation_codes。

路由:resource(单数资源)

用于当前上下文中只有一个、不需要 :id 的资源,例如 resource :session(当前用户的登录会话)。

请求 路径 控制器#动作
POST /session sessions#create
GET /session sessions#show
PATCH/PUT /session sessions#update
DELETE /session sessions#destroy
  • 路径是单数,没有 :id,也没有 index。
  • 控制器名会自动转成复数:resource :session 对应 SessionsController。
  • 名字写单数:resource :session、resource :profile、resource :me。

动作数量

  • 本项目是 API 模式,不生成 new 和 edit:resources 有 5 个动作,resource 有 4 个。
  • 非 API 模式下才是 7 个和 6 个,并且有 /items/:id/edit 这类路径。

对照表

写法 路径 找的控制器 结果
resources :sessions /sessions、/sessions/:id SessionsController 正确
resource :session /session SessionsController 正确
resources :session /session、/session/:id SessionController 找不到控制器
resource :sessions /sessions SessionsController 能用,但不合约定

命名空间

1
2
3
4
5
6
namespace :api do
  namespace :v1 do
    resources :validation_codes, only: [ :create ]
    resource :session, only: [ :create, :destroy ]
  end
end
  • 路径加上 /api/v1 前缀,控制器加上 Api::V1:: 模块前缀。
  • 单复数规则不变。

生成器命令:bin/rails g controller

格式:bin/rails g controller 名字 [动作...]

  • 名字要自己写复数,生成器不会转换,写什么就生成什么。
    • bin/rails g controller api/v1/sessions
    • 生成 app/controllers/api/v1/sessions_controller.rb,类名 Api::V1::SessionsController。
    • bin/rails g controller api/v1/session
    • 生成 session_controller.rb,类名 Api::V1::SessionController,不合约定。
  • 不需要加 _controller 后缀。加了也会被自动去掉,
    • api/v1/users_controller 和 api/v1/users 结果相同,不会生成 users_controller_controller.rb。
  • 斜杠表示命名空间:api/v1/sessions 对应目录 api/v1/ 和模块 Api::V1::,也可以写成 Api::V1::Sessions。
  • 后面可以跟动作名:bin/rails g controller api/v1/sessions create destroy 会生成这两个空方法。
  • 带动作名时加上 --skip-routes。
    • 否则它会往 config/routes.rb 里加 get 'sessions/create' 这种路由,需要手动删掉再换成 resource/resources。
  • 会同时生成 RSpec 测试文件 spec/requests/api/v1/sessions_spec.rb。
  • 不确定会生成什么时,加 --pretend 只预览、不写文件。

单复数速查

东西 单复数 例子
模型类 单数 ValidationCode
数据库表 复数 validation_codes
控制器类 复数 ValidationCodesController
resources 路由 复数 resources :validation_codes
resource 路由 单数 resource :session

排查方法

  • 运行 bin/rails routes,查看每条路由实际对应的路径和 控制器#动作。
  • 测试环境设置了 config.action_dispatch.show_exceptions = :rescuable,
    • 找不到控制器时请求返回 404 而不是抛异常。
  • 遇到意外的 404,先看 log/test.log 里有没有 uninitialized constant Api::V1::XxxController,
    • 有就说明路由的单复数写错了。

8. 可能的报错信息 ⇧

密钥相关报错 ⇧

  • 拿到代码后,可能需要重新创建密钥:https://docs.qq.com/doc/DU3ByQXZWbFpQRHND 。
  • 这一步是可选的,但如果遇到 ActiveSupport::MessageEncryptor::InvalidMessage 报错,那么你就必须重新创建密钥了。

·未完待续·

参考文章

相关文章


  • 作者: Joel
  • 文章链接:
  • 版权声明
  • 非自由转载-非商用-非衍生-保持署名