jwt

2022-07-25  本文已影响0人  求墨者

gem

jwt/ruby-jwt: A ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard. (github.com)

定义

# 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 是资源模型

上一篇 下一篇

猜你喜欢

热点阅读