Home > OS >  How to check for custom attributes
How to check for custom attributes

Time:01-28

I am using a middleware to sanitize asp.net endpoints using HtmlSanitizer as explained here. But its not working for file uploads. So I am trying to use a custom attribute called XssSanitizeIgnore as explained in the discussions section.

I create XssSanitizeIgnore attribute inside My controller as follows,

namespace CarPortal.ReportingServiceApi.Controllers.APIControllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AutoReportController : BaseController
    {
        private readonly IAutoReportService _autoReportService;
        public AutoReportController(IAutoReportService autoReportService) : base()
        {
            _autoReportService = autoReportService;
        }

        [HttpPost]
        [XssSanitizeIgnore]
        [Route("ProcessUploadedFile")]
        public async Task<string> ProcessUploadedFile([FromForm] object formData)
        {

            return await _autoReportService.ProcessUploadedFile((IFormFile)formData);
        }

    }
}

[System.AttributeUsage(System.AttributeTargets.All)]
public class XssSanitizeIgnore: Attribute
{
}

but I am not sure how can I use it inside the middleware

// enable buffering so that the request can be read by the model binders next
            httpContext.Request.EnableBuffering();

            // leaveOpen: true to leave the stream open after disposing, so it can be read by the model binders
            using (var streamReader = new StreamReader(httpContext.Request.Body, Encoding.UTF8, leaveOpen: true))
            {
                var raw = await streamReader.ReadToEndAsync();
                var sanitiser = new HtmlSanitizer();
                var sanitised = sanitiser.Sanitize(raw);

                System.Attribute[] attrs = System.Attribute.GetCustomAttributes(typeof(AutoReportController));
//ignore if XssSanitizeIgnore 
                if (raw != sanitised)
                {
                    throw new BadRequestException("XSS injection detected from middleware.");
                }
            }

            // rewind the stream for the next middleware
            httpContext.Request.Body.Seek(0, SeekOrigin.Begin);
            await _next.Invoke(httpContext);

CodePudding user response:

You can use this snippet code to check if this endpoint has an attribute.

var endpoint = httpContext.GetEndpoint();
var myCustomAttribute = endpoint?.Metadata?.GetMetadata<MyCustomAttribute>();
if (myCustomAttribute is not null)
{
    // ToDo: do someting
}

and if possible use this attribute more than once so you can use this instead.

var endpoint = httpContext.GetEndpoint();
var myCustomAttributes = endpoint?.Metadata?.GetOrderedMetadata<MyCustomAttribute>();
if (myCustomAttributes != null && myCustomAttributes.Any())
{
    // ToDo: do someting
}
  • Related