Jea*_*ean 3 ruby ruby-on-rails token jwt
我正在尝试将过期时间设置为这样的 jwt 令牌:
class JsonWebToken
def self.encode(payload)
payload[:exp] = (2).minutes.from_now.to_i #expire in 2 minutes
JWT.encode(payload, Rails.application.secrets.secret_key_base)
end
def self.decode(token)
return HashWithIndifferentAccess.new(JWT.decode(token, Rails.application.secrets.secret_key_base)[0])
rescue
nil
end
end
Run Code Online (Sandbox Code Playgroud)
但是当我尝试访问 url 时,令牌始终有效。此外,如果我解码令牌,我永远不会在哈希上获得 exp key:value。
任何建议
我正在使用jwt gem
这就是我对用户进行身份验证的方式。
def authenticate_user
user = User.find_for_database_authentication(email: params[:email])
if user.valid_password?(params[:password])
render json: payload(user)
else
render json: {errors: ['Invalid Username/Password']}, status: :unauthorized
end
end
private
def payload(user)
return nil unless user and user.id
{
auth_token: JsonWebToken.encode({user_id: user.id}),
user: {id: user.id, email: user.email}
}
end
Run Code Online (Sandbox Code Playgroud)
使用 curl 的示例:
curl -X POST -d email="a@a.com" -d password="changeme" http://localhost:3000/auth_user
Run Code Online (Sandbox Code Playgroud)
此卷曲返回:
{"auth_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.wPPX7T6WJ5K8ucjZF_l8-9mG7IzabcusLeWw1UOhhTM","user":{"id":1,"email":"a@a.com"}}
Run Code Online (Sandbox Code Playgroud)
然后在我的 rails 控制台上:
JWT.decode("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.wPPX7T6WJ5K8ucjZF_l8-9mG7IzabcusLeWw1UOhhTM", Rails.application.secrets.secret_key_base)
Run Code Online (Sandbox Code Playgroud)
并得到:
[{"user_id"=>1}, {"typ"=>"JWT", "alg"=>"HS256"}]
Run Code Online (Sandbox Code Playgroud)
如您所见,即使我在这一行设置了过期时间,令牌也始终有效:
def self.encode(payload)
payload[:exp] = (2).minutes.from_now.to_i #expire in 2 minutes <<--- This one
JWT.encode(payload, Rails.application.secrets.secret_key_base)
end
Run Code Online (Sandbox Code Playgroud)
这是一个简单的测试,显示 JWT gem 正常工作:
require 'JWT'
class JsonWebToken
def self.encode(payload, expiration)
payload[:exp] = expiration
JWT.encode(payload, 'SECRET')
end
def self.decode(token)
return JWT.decode(token, 'SECRET')[0]
rescue
'FAILED'
end
end
# expire 2 minutes from now
token = JsonWebToken.encode({ :hello => 'world' }, Time.now.to_i + 120)
puts token # eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJoZWxsbyI6IndvcmxkIiwiZXhwIjoxNDY4Njg3OTc1fQ.NhIsdEa0Q7Wl5Dx6kyJvSZY6E8ViJ5Kooo7rKr2OBPg
puts JsonWebToken.decode(token) # {"hello"=>"world", "exp"=>1468687975}
# expire 2 minutes ago
token = JsonWebToken.encode({ :hello => 'world' }, Time.now.to_i - 120)
puts token # eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJoZWxsbyI6IndvcmxkIiwiZXhwIjoxNDY4Njg3NzM1fQ.kDD_WWN3ZTTdFXQvYEgm1CgDaE1mEZxjMvQkQEq4HX8
puts JsonWebToken.decode(token) # FAILED
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11476 次 |
| 最近记录: |