mauriziopatino
mauriziopatino

Reputation: 49

Does sharing a DTO class between methods create vulnerabilities regarding 'extra' properties?

I'm creating a API where I have two methods. The first one is a Register method:

[HttpPost("register")]
public async Task<ActionResult<User>> Register(UserDto request)
{
  // User validation
}

The second is a Login method:

[HttpPost("login")]
public async Task<ActionResult<User>> Login(UserDto request)
{
  // User validation
}

Here is my DTO class:

public class UserDto
    {
        public string Username { get; set; } = string.Empty;
        public string Password { get; set; } = string.Empty;
        public string Name { get; set; } = string.Empty; 
        public string Lastname { get; set; } = string.Empty;
        public string PhoneNumber { get; set; } = string.Empty;
    }

The main problem is that I need different attributes for each method. In the REGISTRATION method, I need all the fields: Username, Password, Name, LastName, PhoneNumber). Whereas in the LOGIN method I just need the Username & Password fields.

I'm concerned about system vulnerabilities by using the same DTO class between methods (which works, but might expose extra fields that aren't needed). Do I need to create another DTO class with just the fields I need for each method? Is there another way to accomplish this?

Upvotes: 2

Views: 211

Answers (1)

Kurubaran
Kurubaran

Reputation: 8902

Another approach you could use is to move the common properties to a base class, and inherit the base class wherever you need it. for an instance, you could move UserName and Password to a base class.

public class UserBaseDto
{
   public string Username { get; set; } = string.Empty;
   public string Password { get; set; } = string.Empty;
}


public class UserDto : UserBaseDto
{
   public string Name { get; set; } = string.Empty; 
   public string Lastname { get; set; } = string.Empty;
   public string PhoneNumber { get; set; } = string.Empty;
}

But it’s best to avoid using inheritance in DTOs unless absolutely necessary. If you do need to use inheritance, try to keep the base class as simple as possible so that any changes won’t have too much of an impact on the derived classes

Upvotes: 2

Related Questions