0

I need help on how to protect/secure my Api upload route when an upload is performed.

In a razor page I have a RadzenUpload control like this:

<RadzenUpload Accept="image/*" Progress=@OnProgress class="w-100" Url=@($"/api/upload/uploadfirmlogo")/>

So the upload will be posted at /api/upload/uploadfirmlogo

and this is my controller:

[ApiController]
[Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
//[Authorize]
public class UploadController : Controller
{     
    private readonly IWebHostEnvironment environment;
    
    public UploadController(IWebHostEnvironment environment)
    {
        this.environment = environment;            
    }

    [HttpPost("UploadFirmLogo")]
    public async Task<IActionResult> UploadFirmLogoAsync(IFormFile[] files)
    {
        try
        {
            if (HttpContext.Request.Form.Files.Any())
            {
                var file = HttpContext.Request.Form.Files[0];
                string path = Path.Combine(environment.WebRootPath, "images", "logos", file.FileName);
                using (var stream =
                       new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
            }
            return StatusCode(200);
        }
        catch (Exception ex)
        {
            return StatusCode(500, ex.Message);
        }
    }
}

My application is using AuthenticationStateProvider for login process. But I don't know how to protect my upload route and allow access only for the current logged in user.

D A
  • 1,724
  • 1
  • 8
  • 19

1 Answers1

0

You can add protection to whole controllers on individual routes using the [Authorize] Property.

[Authorize]
[HttpPost("UploadFirmLogo")]
public async Task<IActionResult> UploadFirmLogoAsync(IFormFile[] files)
{ 
    ...
}

or

[ApiController]
[Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
[Authorize]
public class UploadController : Controller
{  
  ...
}

Adding it to the controller means that every endpoint on the route will require the authorization middleware to be run in. But if you wish to only protect a single route, just use the [Authorize] property above any route you'd like to protect.

Mark Barton
  • 847
  • 6
  • 15
  • Is not working, because the upload is not sending also a session token or a Bearer token. I get a 500 response code – D A May 31 '23 at 09:54
  • a 500 indicates something fundamentally wrong with your server's code, not an issue with your authentication (that would return a 401, or a 403 for authorization). What error message do you get in your catch block? – Mark Barton May 31 '23 at 10:01
  • Is not getting there. Is just 500 without any explanations. – D A May 31 '23 at 10:32
  • surely you must be getting some kind of error in the API console? It sounds to me that your API has some issues in its setup, middleware, service injection, or assembly issues – Mark Barton May 31 '23 at 10:52