Looks like what you are asking is how to pass an authorization header when using html audio
tag. Here you can see this problem also applies to img
elements with src attribute that points to a secured endpoint. The solutions suggested in the question I linked can be also applied to your scenario. For example your can pass the access token using a query string parameter in the url. You server can then identify those requests and read the token from the query string. SignalR uses this approach and sends the access token in the query string when using WebSockets or ServerSentEvents. You can see in the documentation how it is handled server side:
builder.Services.AddAuthentication(options =>
{
// ...
}).AddJwtBearer(options =>
{
options.Authority = "Authority URL"; // TODO: Update URL
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
// If the request is for your audio endpoint...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
(path.StartsWithSegments("/api/myMp3Endpoint")))
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
If for your environment this is considered a security risk then your other option is to use HttpClient
to fetch the audio as a byte array, convert it to base64 and embed it to your audio element.
@inject HttpClient Http
@if (!string.IsNullOrEmpty(_base64EncodedAudio))
{
<audio controls autobuffer="autobuffer" autoplay="autoplay">
<source src="@($"data:audio/mp3;base64,{_base64EncodedAudio}")" type="audio/mpeg" />
</audio>
}
@code {
private string _base64EncodedAudio;
private async Task GetAudio()
{
var audioBytes = await Http.GetByteArrayAsync(audioUrl);
_base64EncodedAudio = Convert.ToBase64String(audioBytes);
}
}
Using HttpClient
you can pass whatever authorization headers are needed. Demo