ASP.NET Core Web API : conditional serialization

I have a user base with different claims to represent their plans. I want to strip some fields from my objects based on their plans.

I found an answer here: ASP.NET WebAPI Conditional Serialization based on User Role

But it is for HttpClient only, since I can’t use DelegatingHandler in ASP.NET Core 8 (or don’t understand how to) – is there any similar way to manipulate the response of all of my controllers?

For that I can only think of writing custom JsonConverter. I will give you the steps + initial implementation. Further details you will have to figure out.

So, let’s start by implementing sample JsonConverter. Since you want to hide som fields, I assume you know the type and you know, based on user, what to hide and what not. For simplicity, I implemented “return nothing for unauthenticated user”:

public class JsonHideConverter<T> : JsonConverter<T>
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public JsonHideConverter(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }

    public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
    {
        // For other types than specified,
        // do not do nothing, just return full info.
        if (typeof(T) != typeof(WeatherForecast))
        {
            JsonSerializer.Serialize(writer, value);
            return;
        }

        // If user is authenticated, return full info.
        if (_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
        {
            JsonSerializer.Serialize(writer, value);
            return;
        }

        // Hide all together for unauthenticated user.
        return;
    }
}

All good, but it is very tricky to get IHttpContextAccessor into the converter. For that we have to implement another interface IConfigureOptions<JsonOptions> (JsonOptions from Microsoft.AspNetCore.Mvc namespace):

public class ConfigOptions : IConfigureOptions<JsonOptions>
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public ConfigOptions(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void Configure(JsonOptions options)
    {
        options.JsonSerializerOptions.Converters.Add(new JsonHideConverter<WeatherForecast>(_httpContextAccessor));
    }
}

And last, we need to register ConfigOptions as singleton, but it required IHttpContextAccessor, which by default is scoped service, but it is perfectly fine to register it as singleton:

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddSingleton<IConfigureOptions<JsonOptions>, ConfigOptions>();

With all that, you can start using our converter and enhance it with you custom checks based on type of response being written and the user information at hand.

Hope that helps.

References:

  • ASP.Net Core 2.1 – Is it possible to use DI inside of a custom JsonConverter class
  • System.Text.Json how to get converter to utilise default Write() behaviour

According to your requirement, I implement this feature in my side. Here is the detailed steps.

ClaimBasedJsonConverter.cs

using System.Reflection;
using System.Text.Json.Serialization;
using System.Text.Json;

namespace WebApplicationApi
{
    public class ClaimBasedJsonConverter : JsonConverter<object>
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public ClaimBasedJsonConverter(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public override bool CanConvert(Type typeToConvert)
        {
            return typeToConvert.GetProperties().Any(prop => prop.IsDefined(typeof(ClaimSensitiveAttribute), true));
        }

        public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            throw new NotImplementedException();
        }

        public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
        {
            var httpContext = _httpContextAccessor.HttpContext;
            var userClaims = httpContext.User.Claims;

            writer.WriteStartObject();

            foreach (var property in value.GetType().GetProperties())
            {
                var propertyValue = property.GetValue(value);
                var claimSensitiveAttribute = property.GetCustomAttribute<ClaimSensitiveAttribute>();

                if (claimSensitiveAttribute == null)
                {
                    writer.WritePropertyName(property.Name);
                    JsonSerializer.Serialize(writer, propertyValue, property.PropertyType, options);
                    continue;
                }

                var hasRequiredClaim = userClaims.Any(c =>
                    c.Type == claimSensitiveAttribute.ClaimType &&
                    claimSensitiveAttribute.ClaimValues.Contains(c.Value));

                if (hasRequiredClaim)
                {
                    writer.WritePropertyName(property.Name);
                    JsonSerializer.Serialize(writer, propertyValue, property.PropertyType, options);
                }
            }

            writer.WriteEndObject();
        }
    }

}

ClaimSensitiveAttribute.cs

namespace WebApplicationApi
{
    [AttributeUsage(AttributeTargets.Property)]
    public class ClaimSensitiveAttribute : Attribute
    {
        public string ClaimType { get; }
        public string[] ClaimValues { get; }

        public ClaimSensitiveAttribute(string claimType, params string[] claimValues)
        {
            ClaimType = claimType;
            ClaimValues = claimValues;
        }
    }

}

Register it

using WebApplicationApi;

var builder = WebApplication.CreateBuilder(args);
// Register it 
builder.Services.AddHttpContextAccessor();

builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.Converters.Add(new ClaimBasedJsonConverter(builder.Services.BuildServiceProvider()?.GetRequiredService<IHttpContextAccessor>()));
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
// Make sure you have this line
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

Apply it in model

namespace WebApplicationApi.Models
{
    public class User
    {
        public string? Name { get; set; }
        public string? Email { get; set; }

        [ClaimSensitive("Plan", "Free", "Premium")]
        public string? SensitiveData { get; set; }

        [ClaimSensitive("Role", "Admin")]
        public string? AdminNotes { get; set; }
    }
}

Test it in controller

using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using WebApplicationApi.Models;

namespace WebApplicationApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class UsersController : ControllerBase
    {

        [HttpGet]
        public IActionResult GetUser()
        {
            // If change Plan value to `Unknown`, 
            //{
            // "Name": "John Doe",
            // "Email": "[email protected]",
            // "AdminNotes": "Admin Only Notes"
            //}
            var claims = new List<Claim>
            {
                
                new Claim("Plan", "Premium"),  
                new Claim("Role", "Admin")     
            };

            var identity = new ClaimsIdentity(claims, "TestAuth");
            var user = new ClaimsPrincipal(identity);
            HttpContext.User = user;

            var userModel = new User
            {
                Name = "John Doe",
                Email = "[email protected]",
                SensitiveData = "Sensitive Premium Info",
                AdminNotes = "Admin Only Notes"
            };

            return Ok(userModel);
        }

    }
}

Test Result

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật