Get a Pentest and security assessment of your IT network.

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.

  • Security Risk: Unauthorized data access
  • Common Scenario: User profiles, order details, etc.

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.

  • Benefits: Decoupling, security, versioning
  • Example: Create a UserDto class with only the properties you want to expose publicly (e.g., ID, username).

4. Control Access with Authorisation

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

  • Implement authorisation checks: Before returning any data, verify that the current user is allowed to view it.
  • Example (pseudo-code):
    if (!UserHasPermission(currentUser, userId)) {
      return null; // Or throw an exception
    }
    

5. Avoid Using IDs Directly in URLs

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

  • Use GUIDs: Globally Unique Identifiers (GUIDs) are much harder to predict.
    // Bad - Predictable integer ID
    /users/123
    
    // Good - Random GUID
    /users/a1b2c3d4-e5f6-7890-1234-567890abcdef
    

6. Consider Indirect Object References

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

  • Example: Use usernames or email addresses instead of user IDs.
Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation