簡體   English   中英

如何在Rails中使用中間件通過JWT獲取current_user_id?

[英]how to use middleware in rails to get current_user_id by JWT?

我是Rails的新手,我通常在Express上使用中間件通過解碼的JWT獲取user.id,類似這樣

/middleware/jwt.js

const authentic = async (req, res, next) => {
  const token = req.header("token");
  if (!token) {
    res.status(400).json({ error: "no token " });
  } else {
    try {
      const decoded = verifyJwt(token);
      const isAuth = await Person.findOne({ _id: decoded._id });
      if (!isAuth) {
        res.status(400).json({ error: `you are not authentic` });
      } else {
        // keys : _id, role, username
        req.user = decoded;
        next();
      }
    } catch (e) {
      next(e);
    }
  }
};

export default authentic;

然后在路由上使用它, app.use(authentic)這樣我可以在我關聯或填充的每個查詢上獲取req.user.id

在rails中,如何使用中間件,並要求該真實中間件獲得current_user_id? 所以我可以將其與其他模型相關聯,我僅使用API​​的rails,我希望使用JWT來獲得一些實現,而無需像devise或其他任何寶石

這是JWT的重要一環:

/lib/json_web_token.rb

class JsonWebToken
 class << self
   def encode(payload, exp = 24.hours.from_now)
     payload[:exp] = exp.to_i
     JWT.encode(payload, Rails.application.secrets.secret_key_base)
   end

   def decode(token)
     body = JWT.decode(token, Rails.application.secrets.secret_key_base)[0]
     HashWithIndifferentAccess.new body
   rescue
     nil
   end
 end
end

如果rails摘錄只是令牌(de)編碼器,則實際的中間件看起來非常相似,它應該是可調用的對象(可以是proc / lambda,或更常見的是帶有call方法的實例):

class SomeMiddleware
  def initialize(app, params)
    @app = app
  end

  def call(env)
    @app.call(env)
  end
end
# application.rb
config.middleware.use SomeMiddleware, some_optional: "params"

但是對於身份驗證,您不必使用中間件,在大多數情況下, ApplicationControllerbefore_action就足夠了。

您也可以考慮使用一些寶石,例如敲門devise-jwt

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM