html - 如何根据 Web API/Asp.Net Identity 验证 HTML-5 音频下载请求?

标签 html asp.net-web-api asp.net-identity owin html5-audio

我需要从我的 Web API 流式传输音频。在标准 HTML-5 中,音频 src 属性设置为来自 WebAPI 的音频的 URI。

问题是:使用 Asp.Net Identity 保护的 Web API 需要在 header 中传递不记名 token ,但是 HTML AUDIO TAG 不允许我们这样做。我最终被排除在两个选择之外:

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.

上面提到的第一种方法是不可行的,因为如果我们在本地下载音频,我们将错过 Web API 提供的流媒体功能。

您能否协助方法 2,即在 Web API 端,我们可以从 URL 读取不记名 token ,然后启动 Asp.Net 身份验证?

最佳答案

创建这个提供者类

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);
    }
}

在 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()
});

现在它将像这样从 url "..../?access_token=xxxxxxx"获取 token 并尝试验证。

关于html - 如何根据 Web API/Asp.Net Identity 验证 HTML-5 音频下载请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34473724/

相关文章:

asp.net - 无法使用 Microsoft OAuth v2 登录 Microsoft 个人帐户

jquery - 在 syncfusion 柱形图系列中使用隐藏字段

javascript - 使用自动完成和相同的 ID 填充多个字段

javascript - Accordion 菜单(单击时)会影响图像在下一个表格单元格中的位置

c# - 将 ASP.NET Identity 集成到现有的 DbContext

asp.net-mvc-5 - ASp.net Identity 2.0 示例 - Controller 构造函数、DB 构造函数和 Owin 中间件的重用

html - CSS:背景图片问题

c# - Web Api 2 根据接受 header 确定 Controller 返回类型

c# - .Net CORE Web API 无缓存但仍然发生

c# HttpClient PostAsync with async and await 不工作