我对此感到有点困惑。我对rails API有点新意。当用户访问www.example.com/products时 - 他仍然可以查看正常的网页,但如果他请求www.example.com/products.json,他应该使用令牌进行身份验证,否则应该拒绝访问。 在普通的rails应用程序中,默认情况下我们可以使用GET / pins或/pins.JSON,如下所示:
但是,如果我只想验证GET /pins.JSON或其他什么东西,那么该怎么办.JSON?这有可能吗?
我确实看过rails_api gem给某些tutorials建议使用rails_api创建rails应用程序,这会创建整个应用程序作为API而无需正常的网页访问。
有人可以按照我想要的方式建议吗?
class PinsController < ApplicationController
before_action :set_pin, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user! , except: [:index, :show]
before_action :correct_user , only: [:edit, :udpate, :destroy]
# GET /pins
# GET /pins.json
def index
@pins = Pin.all.order("created_at DESC").paginate(:page => params[:page])
end
def show
end
def new
@pin = current_user.pins.build
end
def edit
end
# POST /pins
# POST /pins.json
def create
@pin = current_user.pins.build(pin_params)
respond_to do |format|
if @pin.save
format.html { redirect_to @pin, notice: 'Pin was successfully created.' }
format.json { render :show, status: :created, location: @pin }
else
format.html { render :new }
format.json { render json: @pin.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /pins/1
# PATCH/PUT /pins/1.json
def update
respond_to do |format|
if @pin.update(pin_params)
format.html { redirect_to @pin, notice: 'Pin was successfully updated.' }
format.json { render :show, status: :ok, location: @pin }
else
format.html { render :edit }
format.json { render json: @pin.errors, status: :unprocessable_entity }
end
end
end
# DELETE /pins/1
# DELETE /pins/1.json
def destroy
@pin.destroy
respond_to do |format|
format.html { redirect_to pins_url, notice: 'Pin was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_pin
@pin = Pin.find(params[:id])
end
def correct_user
@pin = current_user.pins.find_by(id: params[:id])
redirect_to pins_path, notice: "Not authorized to edit this pin" if @pin.nil?
end
# Never trust parameters from the scary internet, only allow the white list through.
def pin_params
params.require(:pin).permit(:description, :image)
end
end
答案 0 :(得分:1)
最简单的方法是创建before_filter :authenticate_json
并在请求json时强制执行身份验证
before_filter :authenticate_json
def authenticate_json
if request.path_parameters[:format] == 'json'
authenticate!
end
end