In order to redirect users to a custom web page each time params
contain a redirect_uri
value I am evaluating to use a custom redirect_to
method this way (by @kiddorails):
class ApplicationController < ActionController::Base
def custom_redirect_to(url)
redirect_to (params[:redirect_uri].present? ? params[:redirect_uri] : url)
end
end
def create
@post = Post.new(params)
if @post.save
custom_redirect_to @post
else
render 'new'
end
end
However I would like to be aware of possible drawbacks and to receive support for adopting the above solution.
Allowing a redirect target to be set through a URL parameter without any validation is potentially dangerous for your users, because it makes fishing attempts easier.
An attacker can send links to your users such as
http://my-trusted-site.com/some/action/path?redirect_uri=malicious-site-that-looks-like-trusted-site.com
, and many users will only see the domain part and fail to realize where they end up after clicking that link.
The Open Web Application Security Project (OWASP) therefor considers this a vulnerability:
It's important that you check the redirect_uri parameter carefully before executing the redirect.
But since proper validation is tricky and prone to errors, an even better idea is not to accept URI parameters in the first place, but to allow certain keywords instead that specify where the user will be redirected.
You can now define any number of allowed keywords in advance which may be used as the
?redirect_to=
parameter:If
?redirect_to=edit
is set, the user is redirected back to the edit page. If the parameter is not set or contains an unspecified keyword, she is redirected to the defaultpost_path(@post)
instead.I agree with what janfoeh said above. But to implement your requirement, I hacked around in Rails code of redirection to make it simpler.
Make a file config/initializers/redirecting.rb with:
In your app/controllers/application_controller.rb :
And Voila! Now you can continue to use the original
redirect_to
, and wheneverredirect_uri
is supplied in the url, it will set that url in session and automatically override. :)Note: I am clearing
session[:redirect_uri]
only whenredirect_to
is called. You can easily modify that behavior to reset this session depending upon the requirement.