How to hide Model members from certain users?

Shant Hagopian 21 Reputation points
2022-05-05T15:14:00.547+00:00

I am building an API that will serve users with different administration levels (roles)

I have the following model (redacted for brevity)

public class Job
{
    public Guid JobId { get; set; }
    public string Name{ get; set; }
    public string CommentsAdmins { get; set; }
}

When an admin user calls the API controller, I want the API to return the entire model above. But when a regular user calls the API, I want the model to return the same model, minus CommentsAdmins

public class Job
{
    public Guid JobId { get; set; }
    public string Name{ get; set; }
}

I'm not comfortable to use a nullable string? because I believe that's a dirty way to do it. Also I don't want the field to be visible in my mobile app code, which may be publicly visible if somebody tries to decompile the mobile app binaries.

Additionally, creating multiple models for multiple user levels doesn't feel intuitive as well.
Having Multiple model means there will duplicates of the same code, which makes it a lot more cumbersome to debug and in case of any change, the possibility of forgetting to change one of the model's redacted copies will be higher. Additionally, this method requires copying object values to the redacted models for every organizational role level.

What's the best way to go about this?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,397 questions
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
7,397 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 61,491 Reputation points
    2022-05-05T15:26:46.937+00:00

    the default serializer can be configured, to suppress null values. if you don't like this you have a couple options, depending on the permission design,

    1) if you want full control, your best solution is a custom serializer. You could add role attributes to the properties

    2) if you only have a couple levels of permission, and they are additive, you could use inheritance.

    public class MyModel {..}
    public class MyModelPower : MyModel {public string SomePowerField {get; set;}
    public class MyModelAdmin : MyModelPower {public string SomeAdminField {get; set;}


0 additional answers

Sort by: Most helpful