Proper validation of user sessions or tokens to secure web services.
def show(conn, %{"id" => id}) do
user = Repo.get(User, id)
render(conn, "show.json", user: user)
end
This code sample is a simple controller action in a Phoenix API that retrieves and sends user data based on the user id received from the request parameters. The problem here is there are no authorization checks in place, meaning any authenticated user or even unauthenticated users can retrieve any user's information just by changing the id parameter. This poses a significant risk as it can lead to unauthorized access to confidential user information.
def show(conn, %{"id" => id}) do
requester = get_current_user(conn)
if requester && requester.id == id do
user = Repo.get(User, id)
render(conn, "show.json", user: user)
else
conn |> put_status(:forbidden) |> json(%{message: 'Forbidden'})
end
end
In the secure code sample, before fetching the user data, an authorization check is added to ensure that the requester is the same as the user they are trying to access. If the check fails, a 403 Forbidden response is returned, thus preventing unauthorized access.