基本身份验证路由

时间:2016-11-10 02:55:14

标签: ruby-on-rails basic-authentication

我正在尝试使用

完成某种方式
http_basic_authenticate_with name: "admin", password: "secret"

使用用户的电子邮件和密码进行身份验证,而不是使用硬编码密码。这是我的控制器类的其余部分。

class Api::V1::UserInfosController < ApplicationController
  before_action :set_user_info, only: [:show, :edit, :update, :destroy]
  http_basic_authenticate_with name: "admin", password: "secret"

  # GET /user_infos
  def index
    @user_infos = UserInfo.all
  end

  respond_to :json

  def show
    respond_with UserInfo.find(params[:id])
  end

  # GET /user_infos/new
  def new
    @user_info = UserInfo.new
  end

  # GET /user_infos/1/edit
  def edit
  end

  # POST /user_infos
  def create
    @user_info = UserInfo.new(user_info_params)

    if @user_info.save
      redirect_to @user_info, notice: 'User info was successfully created.'
    else
      render :new
    end
  end

  # PATCH/PUT /user_infos/1
  def update
    if @user_info.update(user_info_params)
      redirect_to @user_info, notice: 'User info was successfully updated.'
    else
      render :edit
    end
  end

  # DELETE /user_infos/1
  def destroy
    @user_info.destroy
    redirect_to user_infos_url, notice: 'User info was successfully destroyed.'
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user_info
      @user_info = UserInfo.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def user_info_params
      params.require(:user_info).permit(:artist, :email, :password)
    end
end

任何帮助都将非常感谢! :)

1 个答案:

答案 0 :(得分:2)

我建议您使用Devise gem进行身份验证。它易于使用,并拥有庞大的社区支持。

但是,在回答您的问题时,您可以执行的操作是遵循ActionController::HttpAuthentication::Basic文档中的示例并实现以下目标:

class Api::V1::UserInfosController < ApplicationController
  before_filter :set_current_user

  private

  def set_current_user
    @current_user ||= authenticate_or_request_with_http_basic do |u, p|
      User.find(email: u, password: p)
    end
  end
end

User是您的授权用户的型号。