Prevent unauthorized redirection to potentially malicious external sites
def handle_req(%Plug.Conn{params: params} = conn, _) do
redirect_to = Map.get(params, "redirect_to")
conn |> redirect(external: redirect_to)
end
The code above is vulnerable as it takes a 'redirect_to' parameter from the request and uses it directly to redirect the user. An attacker can manipulate the 'redirect_to' parameter to redirect users to a malicious website.
def handle_req(%Plug.Conn{params: params} = conn, _) do
redirect_to = Map.get(params, "redirect_to")
allowed_urls = ["http://safe1.com", "http://safe2.com"]
if redirect_to in allowed_urls, do: conn |> redirect(external: redirect_to)
end
The secure code checks the 'redirect_to' parameter against a list of allowed URLs before making the redirection. This ensures that the user can't be redirected to a malicious website even if they manipulate the 'redirect_to' parameter.