Prevent potential attacks via HTTP headers by validating the data received
defmodule MyAppWeb.MyController do
use MyAppWeb, :controller
def show(conn, _params) do
# No header validation
user_token = get_req_header(conn, "user-token")
item = MyApp.get_item(user_token)
json(conn, item)
end
end
This code is vulnerable because it doesn't validate the 'user-token' header. An attacker can inject potentially harmful content into this header to exploit potential vulnerabilities or achieve an XSS attack.
defmodule MyAppWeb.MyController do
use MyAppWeb, :controller
def show(conn, _params) do
user_token = get_req_header(conn, "user-token")
if validate_token(user_token) do
item = MyApp.get_item(user_token)
json(conn, item)
else
send_resp(conn, 400, "Invalid user-token header")
end
end
defp validate_token(token) do
# Implement your validation logic here
end
end
This code is safe because it validates the 'user-token' header before using it. If the header contains invalid data, it returns an error response instead of passing the harmful content to 'MyApp.get_item'.