Javascript 如何在rails中使用中间件通过JWT获取当前用户id?
我是Rails新手,我通常在Express上使用中间件通过解码JWT获取user.id, 是这样的吗 /middleware/jwt.jsJavascript 如何在rails中使用中间件通过JWT获取当前用户id?,javascript,ruby-on-rails,ruby,authentication,jwt,Javascript,Ruby On Rails,Ruby,Authentication,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 { c
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;
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
然后我在路线上使用它,app.use(authentic)
因此,我可以在我关联或填充的每个查询上获得req.user.id
在rails中,如何使用中间件并要求真实的中间层获取当前的用户id??所以我可以把它和其他模型联系起来,
我只使用railsforapi,我很想在没有任何gem的情况下实现它,比如design
或其他,只使用JWT
以下是JWT的导轨:
/lib/json\u web\u token.rb
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;
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
类JsonWebToken
类如果rails摘录是唯一的令牌(de)编码器,那么实际的中间件看起来非常相似,它应该是一个可调用的对象(proc/lambda,或者更常见的是带有call
方法的实例):
但对于身份验证,您不必将其作为中间件,在大多数情况下,在应用程序控制器中的操作之前
就足够了
此外,您还可以研究使用一些gem,如或,前提是rails摘录是唯一的令牌(de-)编码器,实际的中间件看起来非常相似,它应该是一个可调用对象(proc/lambda,或者更常见的是一个带有调用
方法的实例):
但对于身份验证,您不必将其作为中间件,在大多数情况下,在应用程序控制器中的操作之前
就足够了
你也可以研究使用一些宝石,比如or,我知道关于敲打,但我不知道你现在使用的设备jwt??仅用于api我会使用knock
我知道关于敲打,但我不知道设备jwt,你现在使用的设备??仅用于api我会使用knock