Blog | G5 Cyber Security

Secure Code: Avoid Object References

TL;DR

Directly exposing objects can create security risks. This guide shows you how to avoid it by returning only the data needed, using Data Transfer Objects (DTOs), and carefully controlling access.

1. Why Avoid Direct Object References?

Imagine a system where users can request information about other users directly using their ID. If an attacker can guess or manipulate these IDs, they might gain access to sensitive data they shouldn’t see. This is a direct object reference vulnerability.

2. Return Only What’s Necessary

Don’t return the entire object when only a few properties are needed. Create specific responses containing just the required data.

// Bad - Returning the whole user object
public User GetUser(int userId) {
  return _userRepository.GetById(userId);
}

// Good - Returning a DTO with only necessary properties
public UserDto GetUserPublicInfo(int userId) {
  var user = _userRepository.GetById(userId);
  if (user == null) return null;
  return new UserDto { Id = user.Id, Username = user.Username };
}

Here, UserDto is a Data Transfer Object.

3. Use Data Transfer Objects (DTOs)

DTOs are simple classes used to transfer data between layers of your application. They help isolate changes and prevent accidental exposure of internal object structures.

4. Control Access with Authorisation

Even if you’re returning DTOs, always check if the user has permission to access the requested data.

5. Avoid Using IDs Directly in URLs

Using predictable IDs directly in URLs makes it easier for attackers to guess other valid IDs.

6. Consider Indirect Object References

Instead of directly using IDs, use a more abstract identifier that maps to the actual object ID internally.

Exit mobile version