Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to authenticate HTML-5 Audio download request against Web API / Asp.Net Identity?

I need to stream audio from my Web API. In standard HTML-5 audio src attribute is set to URI of the audio from WebAPI.

Problem is: Web API secured with Asp.Net Identity requires bearer token to be passed in the headers, however HTML AUDIO TAG doesn't allow us to do. I am finally left out with two alternatives:

Approach 1. Download the HTML using XHR request & play locally.

Approach 2. Pass headers via query string. So that we could inject the token into OWIN pipeline at point of time during request processing.

First approach mentioned above is not viable, because if we download the audio locally we would miss out streaming features provided by Web API.

Could you please assist with approach-2 i.e. so that on Web API side we could read bearer token from URL & then initiate Asp.Net Identity Authentication?

like image 587
Abhijeet Avatar asked Dec 26 '15 17:12

Abhijeet


1 Answers

Create this provider class

public class QueryStringOAuthBearerProvider : OAuthBearerAuthenticationProvider
{
    public override Task RequestToken(OAuthRequestTokenContext context)
    {
        var value = context.Request.Query.Get("access_token");

        if (!string.IsNullOrEmpty(value))
        {
            context.Token = value;
        }

        return Task.FromResult<object>(null);
    }
}

Use it in Startup.cs

OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new ApplicationOAuthProvider(PublicClientId),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    // In production mode set AllowInsecureHttp = false
    AllowInsecureHttp = true                
};

// Enable the application to use bearer tokens to authenticate users

//app.UseOAuthBearerTokens(OAuthOptions);   // old line

app.UseOAuthAuthorizationServer(OAuthOptions); // new line

// Enable the application to retrieve tokens from query string to authenticate users
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
    Provider = new QueryStringOAuthBearerProvider()
});

Now it will get token from url "..../?access_token=xxxxxxx" like that and try it to validate.

like image 101
Deniz Kısır Avatar answered Oct 11 '22 20:10

Deniz Kısır