如何更改特定控制器的请求参数

时间:2019-03-18 04:49:59

标签: ruby-on-rails jwt

我正在编写具有JWT身份验证的应用程序,输入是通过request.query_parameters完成的,即通过诸如example.com?Authorization=token之类的链接,输入是有效的,但是当我调用任何操作时,它会将我重定向到索引而不保存令牌并删除401。我的应用程序控制器

  protected

  def authenticate_request!
    if !payload || !JsonWebToken.valid_payload(payload.first)
      return invalid_authentication
    end

    load_current_user!
    invalid_authentication unless @current_user
  end

  def invalid_authentication
    render json: {error: 'Invalid Request'}, status: :unauthorized
  end

  private
  def payload
    auth_header = request.query_parameters['Authorization']
    token = auth_header.split(' ').last
    JsonWebToken.decode(token)
  rescue
    nil
  end

  def load_current_user!
    @current_user = User.find_by(id: payload[0]['user_id'])
  end

main_controller

class MainController < ApplicationController
  before_action :authenticate_request!

  # GET /
  def index
  end

以下是我正在做的示例的日志:

Started GET "/?Authorization=eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1LCJleHAiOjE1NTMyMzQxMzgsImlzcyI6Imlzc3Vlcl9uYW1lIiwiYXVkIjoiY2xpZW50In0.q9-S1lB_ueu53XREdeXAoO_VKeEE6nBV1-d1zkO5o3M" for ::1 at 2019-03-16 21:50:09 +0600 Processing by MainController#index as HTML   Parameters: {"Authorization"=>"eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1LCJleHAiOjE1NTMyMzQxMzgsImlzcyI6Imlzc3Vlcl9uYW1lIiwiYXVkIjoiY2xpZW50In0.q9-S1lB_ueu53XREdeXAoO_VKeEE6nBV1-d1zkO5o3M"} User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT ?  [["LIMIT", 1]]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT ?  [["LIMIT", 1]]   User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 5], ["LIMIT", 1]]   Rendering main/index.html.erb within layouts/application   Rendered main/index.html.erb within layouts/application (0.3ms)   Rendered shared/_header.html.erb (1.3ms) Rendered shared/modals/_create_room_modal.html.erb (4.7ms) Completed 200 OK in 110ms (Views: 104.3ms | ActiveRecord: 0.6ms)


Started GET "/u/gl-fcsveclewrto/recordings" for ::1 at 2019-03-16 21:50:13 +0600 Processing by UsersController#recordings as HTML   Parameters: {"user_uid"=>"gl-fcsveclewrto"}   User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT ?  [["LIMIT", 1]]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT ?  [["LIMIT", 1]] Redirected to http://localhost:3000/ Completed 302 Found in 4ms (ActiveRecord:
0.5ms)


Started GET "/" for ::1 at 2019-03-16 21:50:13 +0600 Processing by MainController#index as HTML   User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT ?  [["LIMIT", 1]]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT ?  [["LIMIT", 1]] Filter chain halted as :authenticate_request! rendered or redirected Completed 401 Unauthorized in 4ms (Views: 0.4ms | ActiveRecord: 0.5ms)

据我了解,他无法保存状态并将其继续下去吗?还是我应该以某种方式在前端处理令牌并保存,请告诉我我做错了什么?

0 个答案:

没有答案