【山竹记账后端】11.中间件与鉴权


大纲链接 §

[toc]


1. 把 JWT 做成中间件 ⇧

为什么要用中间件 ⇧

查看目前代码 app/controllers/api/v1/mes_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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
    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
  • 会在获取当前用户信息时,读取 header 中的 Authorization 字段,并获取 JWT
  • 再从 JWT 中解码出 user_id 根据 user_id 查询用户信息
  • 以上过程几乎需要在每一个接口重复执行,因此可以创建一个中间件,将这部分代码提取出来
  • 在每个接口中只调用中间件,中间件中再处理这部分逻辑
  • 例如在进入 show 方法前(或进入当前 Controller 前)执行中间件,中间件中再处理这部分逻辑
  • 中间件统一提取 user_id,后续逻辑可直接访问 currentUser 进行查询

    1
    2
    3
    4
    5
    
    flowchart LR
    User[请求方] --> Route[路由]
    Route -->|"① 中间点 / fn"| Controller[Controller]
    Controller --> Response[响应]
    Response -->|"② 中间点"| User

查看 Rails 自带中间件 ⇧

  • 运行命令 bin/rails middleware

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    bin/rails middleware
    use ActionDispatch::HostAuthorization
    use Rack::Sendfile
    use ActionDispatch::Static
    use ActionDispatch::Executor
    use ActionDispatch::ServerTiming
    use ActiveSupport::Cache::Strategy::LocalCache::Middleware
    use Rack::Runtime
    use ActionDispatch::RequestId
    use ActionDispatch::RemoteIp
    use Rails::Rack::Logger
    use ActionDispatch::ShowExceptions
    use ActionDispatch::DebugExceptions
    use ActionDispatch::ActionableExceptions
    use ActionDispatch::Reloader
    use ActionDispatch::Callbacks
    use ActiveRecord::Migration::CheckPending
    use Rack::Head
    use Rack::ConditionalGet
    use Rack::ETag
    run Mangosteen1::Application.routes

自定义中间件 ⇧

config/application.rb

1
2
3
4
5
6
# Push Rack::BounceFavicon at the bottom
config.middleware.use Rack::BounceFavicon

# Add Lifo::Cache after ActionDispatch::Executor.
# Pass { page_cache: false } argument to Lifo::Cache.
config.middleware.insert_after ActionDispatch::Executor, Lifo::Cache, page_cache: false
  • 需要配置一个类 Rack::BounceFavicon
  • 需要配置指定的位置添加 insert_after

手动创建中间件 touch lib/auto_jwt.rb

1
2
3
4
5
6
7
8
9
class AutoJwt
  def initialize(app)
    @app = app
  end

  def call(env)
    [ 200, {}, [ "Hello World!", "Hi!" ] ]
  end
end
  • call为中间件被调用时需要执行的代码
    • 会传参一个 env 可读写对象,包含请求信息、响应信息等
    • 必须返回一个数组,包含状态码、响应头、响应体 [ 200, {}, [ "Hello World!" ] ]

参考


配置自定义中间件 ⇧

config/application.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
28
29
require_relative "boot"

require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "active_storage/engine"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_mailbox/engine"
require "action_text/engine"
require "action_view/railtie"
require "action_cable/engine"
require_relative "../lib/auto_jwt"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Mangosteen1
  class Application < Rails::Application
    config.load_defaults 7.2
    config.autoload_lib(ignore: %w[assets tasks])
    config.api_only = true

    config.middleware.use AutoJwt
  end
end
  • 使用相对路径导入 require_relative "../lib/auto_jwt"
  • 添加自定义中间件 config.middleware.use AutoJwt

运行服务调试中间件 ⇧

  • 运行 bin/rails s
  • 使用 curl ,命令调试终端输入 curl http://Localhost:3000
  • 即可看到返回的 Hello World!Hi!#
  • 不用这个中间件,原本返回 {"message":"Welcome!"}#
  • 再次查看中间件顺序 bin/rails middleware

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    use ActionDispatch::HostAuthorization
    use Rack::Sendfile
    use ActionDispatch::Static
    use ActionDispatch::Executor
    use ActionDispatch::ServerTiming
    use ActiveSupport::Cache::Strategy::LocalCache::Middleware
    use Rack::Runtime
    use ActionDispatch::RequestId
    use ActionDispatch::RemoteIp
    use Rails::Rack::Logger
    use ActionDispatch::ShowExceptions
    use ActionDispatch::DebugExceptions
    use ActionDispatch::ActionableExceptions
    use ActionDispatch::Reloader
    use ActionDispatch::Callbacks
    use ActiveRecord::Migration::CheckPending
    use Rack::Head
    use Rack::ConditionalGet
    use Rack::ETag
    use AutoJwt
    run Mangosteen1::Application.routes
  • 目前这个中间件直接把状态码写死


实现中间件 AutoJwt ⇧

``


2. 创建获取账目接口 ⇧

``


3. 时区导致测试失败 ⇧

``


4. 添加更多测试用例 ⇧

``


5. 更新 API 文档 ⇧

``


6. 修复分页信息 ⇧

``


7. 如何鉴权 ⇧

``


8. 重构 JWT:user.generate_jwt ⇧

``


9. 重构测试代码 ⇧

``


10. 可能的报错信息 ⇧

密钥相关报错

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

·未完待续·

参考文章

相关文章


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