【问题标题】:Serving files with authorization in an Owin self hosted application在 Owin 自托管应用程序中提供具有授权的文件
【发布时间】:2016-07-25 18:58:11
【问题描述】:

我有一个使用 Owin 的自托管应用程序,并且没有任何类型的 ASP.MVC,因此应用程序中没有 web.config。

我已启用 cookie 身份验证和我自己的授权提供程序机制,它们运行良好。 我的应用程序使用以下代码提供一些静态内容:

appBuilder.UseFileServer(new FileServerOptions()
{
    RequestPath = new PathString("/Images"),
    FileSystem = new PhysicalFileSystem(@"./Images"),
});

但是该内容不受 Owin 身份验证的保护,保护文件的最简单方法是什么?

*理想情况下不必实现为自己服务的整个文件。

【问题讨论】:

    标签: c# owin


    【解决方案1】:

    @Cristian T 答案需要扩展。请参阅我的评论:“这仅设置 HTTP 状态代码,在后台它还发送请求的文件,您可以在浏览器控制台的网络选项卡中看到它......”

    因此,要禁用发送文件,您必须在StaticFileContext 之前自己编写响应。 OnPrepareResponse 函数应该是:

    contentFileServer.StaticFileOptions.OnPrepareResponse = (context) => 
    {
        if (context.OwinContext.Authentication.User == null)
        {
            // Reply an unauthorized
            const string unauthorizedBody = "Unauthorized"; // or HTML or anything else
            ctx.OwinContext.Response.StatusCode = 401;
            ctx.OwinContext.Response.Headers.Set("Content-Length", unauthorizedBody.Length.ToString());
            ctx.OwinContext.Response.Headers.Set("Content-Type", "text/html");
            ctx.OwinContext.Response.Write(unauthorizedBody);
        }
    };
    

    这样,服务器返回“未授权”而不是请求的文件。

    【讨论】:

    • 该文件仍将是请求正文的一部分:msdn.microsoft.com/en-us/library/…
    • @Valter 不,我用代理检查过,在这种情况下它不是
    • 好吧,当我查看 firefox/chrome 上的开发人员工具时,我看到文件(位)在 Unauthorized 之后附加到正文。
    • @Valter 你一定是做错了什么,或者可能没有使用相同版本的库。我刚刚重新检查了这个,FF 开发工具和我的调试代理都没有显示该文件。它只是按预期显示“未经授权”。证明:imgur.com/a/JjITh 它在响应的 Content-Length 标头中写了什么?
    【解决方案2】:

    到目前为止,我已经设法以这种方式做到了:

            var contentFileServer = new FileServerOptions()
            {
                RequestPath = new PathString("/Content"),
                FileSystem = new PhysicalFileSystem(@"./Content"),
            };
    
            contentFileServer.StaticFileOptions.OnPrepareResponse = (context) => 
            {
                if (context.OwinContext.Authentication.User == null)
                {
                    // Reply an unauthorized
                    context.OwinContext.Response.StatusCode = 401;
                }
            };
    
            appBuilder.UseFileServer(contentFileServer);
    

    看起来是一种合理的做法。

    【讨论】:

    • 注意:这只是设置 HTTP 状态码,在后台它还会发送请求的文件,您可以在浏览器控制台的网络选项卡中看到它...
    • 该文件仍将是请求正文的一部分:msdn.microsoft.com/en-us/library/…
    • 这不起作用。我已经添加了 NuGet 包和你的代码,构建。但是即使 OwinContext.User 为空,attachments 文件夹下的静态文件仍然可以正常使用。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 2019-04-05
    • 2015-04-13
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    相关资源
    最近更新 更多