我正在创建REST API并在REST API中使用Authorization。每当用户未获得操作授权时,它将使用以下代码重定向到主页
rescue_from CanCan::AccessDenied do |exception|
redirect_to "/", :alert => exception.message
end
对于Rest API方法,我不希望在未经授权的访问时被重定向到此页面。相反,我想显示json
{“Error_msg”:“未授权”}。
我的控制器有以下代码:
authorize_resource :class => false, :only => [:create_or_update]
其中create_or_update
是我要检查授权的操作(方法)。
我的能力.rb在editor
角色
can :create_or_update, :topology
有人可以帮助我不会仅为此操作重定向到主页。
答案 0 :(得分:2)
您可以使用respond_to
来完成 rescue_from CanCan::AccessDenied do |exception|
respond_to do |format|
format.json { render(json: {"Error_msg": "Not Authorized"}, status: :forbidden)}
format.html{
redirect_to "/", :alert => exception.message
}
end
end
答案 1 :(得分:0)
rescue_from CanCan::AccessDenied do |exception|
if exception.action.to_s == "create_or_update"
err ={}
err[:error_id] = "AUTHORIZATION_ERROR"
err[:error_msg] = exception.message
render json: err, status: 403
else
redirect_to "/", :alert => exception.message
end
end