Skip to main content

Improper Authorization Control for Web Services

Need

Proper validation of user sessions or tokens to secure web services.

Context

  • Usage of Elixir (version 1.11 and above) for building scalable and fault-tolerant applications
  • Usage of Phoenix Framework for building web applications

Description

Non compliant code

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.

Steps

  • Add an authorization check before accessing user data.
  • Ensure the user making the request is authorized to access the requested user's data.

Compliant code

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.

References