当前位置: 动力学知识库 > 问答 > 编程问答 >

html5 - 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?

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: