如何制作HTML 5视频标签(通过WebAPI进行身份验证)?

时间:2018-09-11 00:21:17

标签: javascript angular authentication asp.net-web-api cors

我有一个指向我的ASP.NET WebAPI的HTML 5视频标签,该标签需要承载身份验证,我对API的大部分请求如下所示:

GET http://localhost:29080/api/v1/users/me HTTP/1.1
Host: localhost:29080
Connection: keep-alive
Accept: application/json, text/plain, */*
Origin: http://localhost:4200
Authorization: Bearer c66b36fe-fcc1-49da-9b42-dac783768a06
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,fr;q=0.8

由于应用程序托管在其他端口(最终是另一个地址)上,因此需要接受CORS的限制。我已经设置了WebAPI使其符合要求:

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

可悲的是,我的HTML 5视频标签似乎不适用于该设置。

<video 
      crossorigin="use-credentials"
      src="http://localhost:29080/api/v1/entities/470/presentation-video">

我最终得到:

Failed to load http://localhost:29080/api/v1/entities/470/presentation-video: 
The value of the 'Access-Control-Allow-Origin' header in the response must 
not be the wildcard '*' when the request's credentials mode is 'include'. 
Origin 'http://localhost:4200' is therefore not allowed access.

除了:

GET http://localhost:29080/api/v1/entities/470/presentation-video 401 (Unauthorized)

我真的不知道该怎么想,我读过某处可以将承载作为查询字符串传递给

但是我无法使其正常工作...

有什么主意吗?

1 个答案:

答案 0 :(得分:0)

好的,所以对我来说解决方法是:

在我的前端应用程序中:

<video controls crossorigin="anonymous" src="..." </video>

并设置我的视频的src,例如(示例):http://localhost:29080/api/v1/entities/470/presentation-video?access_token=c66b36fe-fcc1-49da-9b42-dac783768a06

由于WebAPI并没有真正检查查询参数(即使它们应该...),因此我们需要一种在接收时将access_token转换为标头的方法,如此处的答案所述:{{3 }}

public void ConfigureAuth(IAppBuilder app)
{
    app.Use(async (context, next) =>
    {
        if (context.Request.QueryString.HasValue)
        {
            if (string.IsNullOrWhiteSpace(context.Request.Headers.Get("Authorization")))
            {
                var queryString = HttpUtility.ParseQueryString(context.Request.QueryString.Value);
                string token = queryString.Get("access_token");

                if (!string.IsNullOrWhiteSpace(token))
                {
                    context.Request.Headers.Add("Authorization", new[] { string.Format("Bearer {0}", token) });
                }
            }
        }

        await next.Invoke();
    });
    // Enable the application to use bearer tokens to authenticate users
    app.UseOAuthBearerTokens(OAuthOptions);
}