Rails忽略重定向



我正在尝试通过oauth2和google-auth-library-ruby库验证用户,以便能够在他们的gmail帐户上执行一些任务。

我的控制器是这样的:

class ExampleController < ApplicationController
def list_email_labels
# Initialize the API
service = Google::Apis::GmailV1::GmailService.new
service.client_options.application_name = "Application Name"
service.authorization = authorize
# Show the user's labels
user_id = "me"
@labels = service.list_user_labels user_id
end
def authorize
token_store = Google::Auth::Stores::FileTokenStore.new file: "token.yaml"
scope = Google::Apis::GmailV1::AUTH_GMAIL_READONLY
client_id = Google::Auth::ClientId.from_hash auth_hash
authorizer = Google::Auth::WebUserAuthorizer.new(client_id, scope, token_store, "/auth/google_oauth2/callback")
user_id = "me"

credentials = authorizer.get_credentials(user_id, request)
if credentials.nil?
redirect_to authorizer.get_authorization_url(login_hint: user_id, request: request), allow_other_host: true
end
credentials
end
def callback
target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request)
redirect target_url
end
def auth_hash
{
"web" => {
"client_id" => [CLIENT_ID],
"project_id" => [PROJECT_ID],
"auth_uri" => 'https://accounts.google.com/o/oauth2/auth',
"token_uri" => 'https://oauth2.googleapis.com/token',
"auth_provider_x509_cert_url" => 'https://www.googleapis.com/oauth2/v1/certs',
"client_secret" => [CLIENT_SECRET],
"redirect_uris" => ['http://localhost:3000/auth/google_oauth2/callback']
}
}
end
end

当我运行这个时,我得到一个错误Google::Apis::AuthorizationError in ExampleController#list_email_labels

错误引用这一行:

@labels = service.list_user_labels user_id

list_email_labels动作。

似乎rails忽略了authorize动作中的redirect_to

任何帮助都非常感谢。

语句在控制器中的redirect_to被执行之后。在redirect_to之后立即终止执行,使用return

redirect_to example_url and return

最新更新