gem
定义
# app/controllers/concerns/json_web_token.rb
require "jwt"
module JsonWebToken
extend ActiveSupport::Concern
SECRET_KEY = Rails.application.secret_key_base
def jwt_encode(payload, exp = 7.days.from_now)
payload[:exp] = exp.to_i
JWT.encode(payload, SECRET_KEY)
end
def jwt_decode(token)
decoded = JWT.decode(token, SECRET_KEY)[0]
HashWithIndifferentAccess.new decoded
end
end
加密-使用
# app/controllers/authentication_controller.rb
class AuthenticationController < ApplicationController
skip_before_action :authenticate_request
def create
@user = User.find_by_email(params[:email])
if @user&.authenticate(params[:password])
token = jwt_encode(user_id: @user.id)
render json: { token: token }, status: :ok
else
render json: { error: "unanthorized" }, status: :unanthorized
end
end
end
User
是资源模型
解密-使用
# app/controllers/application_controller.rb
class ApplicationController < ActionController::API
include JsonWebToken
before_action :authenticate_request
private
def authenticate_request
authorization = request.headers["Authorization"]
token = authorization.split(" ").last if authorization
if authorization && token
decoded_data = jwt_decode(token)
@current_user = User.find(decoded_data[:user_id])
else
render json: "Token expired/invalid", status: 498
end
end
end
User
是资源模型
网友评论