Blazor Server Side Web Application with authorization?

lukas9669

Member
Joined
Feb 7, 2022
Messages
9
Programming Experience
1-3
I have a Blazor Server Side Web Application that uses the default authorization and authentication.

C#:
app.UseAuthentication()
app.UseAuthorization()
I can protect my pages with

C#:
@attribute [Authorize]
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.

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;
  }
}
And in the .razor file

C#:
<a href="@CalculateDownloadLink("file.txt")" target="_blank"></a>
private string CalculateDownloadLink(string filename){
  return $"{NavigationManager.BaseUri}/api/file/download/{filename}"
}
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?
 
 

Latest posts

Back
Top Bottom