如何制作 HTML 5 视频标签,并使用 WebAPI 进行身份验证?

Eho*_*ret 7 javascript authentication cors asp.net-web-api angular

我有一个 HTML 5 视频标签指向我的 ASP.NET WebAPI,它需要承载身份验证,我对 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
Run Code Online (Sandbox Code Playgroud)

由于应用程序托管在不同的端口(最终是不同的地址)上,因此它受到 CORS 的约束。我已经将我的 WebAPI 设置为兼容的:

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
Run Code Online (Sandbox Code Playgroud)

遗憾的是,我的 HTML 5 视频标签似乎无法使用该设置。

<video 
      crossorigin="use-credentials"
      src="http://localhost:29080/api/v1/entities/470/presentation-video">
Run Code Online (Sandbox Code Playgroud)

我最终得到:

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.
Run Code Online (Sandbox Code Playgroud)

除了:

GET http://localhost:29080/api/v1/entities/470/presentation-video 401 (Unauthorized)
Run Code Online (Sandbox Code Playgroud)

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

但我无法让它发挥作用......

任何想法?

Eho*_*ret 6

好吧,我的解决方案是:

在我的前端应用程序中:

<video controls crossorigin="anonymous" src="..." </video>
Run Code Online (Sandbox Code Playgroud)

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

由于 WebAPI 并不真正检查查询参数(即使它们应该......),我们需要一种access_token在接收时将其转换为标头的方法,如此处答案中所述:https ://stackoverflow.com/a/25525470 /4636721

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);
}
Run Code Online (Sandbox Code Playgroud)