I have a Blazor Server Side Web Application that uses the default authorization and authentication.
I can protect my pages with
I have a login page with anonymous access to authenticate. This works fine.
Now I need a way to let the user download files from this authorized pages. Surprisingly I haven't found any straightforward way to do this.
One workaround is to build an API Controller with the filename as a path argument and give the user a link to it.
And in the .razor file
This is a dumbed down version. In reality the filenames are generic. This works too.
Now I want to add Authentication to the API Controller because I don't want anyone guessing filenames. But I don't know how.
Of Course the [Authorize] Attribute doesn't work because the code is outside the circuit scope. I can't figure out how to use any build-in Authorization to make this work.
Is there a better way to download files from a Blazor app?
C#:
app.UseAuthentication()
app.UseAuthorization()
C#:
@attribute [Authorize]
Now I need a way to let the user download files from this authorized pages. Surprisingly I haven't found any straightforward way to do this.
One workaround is to build an API Controller with the filename as a path argument and give the user a link to it.
C#:
[Route("api/[controller]")]
public class FileController{
[HttpGet("download/{filename}")]
public async Task<IActionResult> Download([FromRoute] string filename){
//Do some checks and get file from Filesystem
return file;
}
}
C#:
<a href="@CalculateDownloadLink("file.txt")" target="_blank"></a>
private string CalculateDownloadLink(string filename){
return $"{NavigationManager.BaseUri}/api/file/download/{filename}"
}
Now I want to add Authentication to the API Controller because I don't want anyone guessing filenames. But I don't know how.
Of Course the [Authorize] Attribute doesn't work because the code is outside the circuit scope. I can't figure out how to use any build-in Authorization to make this work.
Is there a better way to download files from a Blazor app?