2016-07-25 58 views
3

我有一個使用Owin自己託管的應用程序,並且沒有任何類型的ASP.MVC,所以應用程序中沒有web.config。在Owin自己託管的應用程序中授權的文件

我已啓用Cookie身份驗證和我自己的授權提供程序機制,它工作得很好。 我的應用程序中使用的下一個代碼提供一些靜態的內容:

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

但這些內容不被Owin認證保護,這將是保護文件的最簡單的方法?

*理想情況下不需要執行整個文件服務自己。

回答

5

到目前爲止,我已經成功地做到這一點這樣:

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

看起來那麼這是一種合理的方式。

+1

注:這僅設置HTTP狀態代碼,引擎蓋下,它也發送請求的文件,你可以看到它在網絡選項卡中的瀏覽器控制檯... – Darxis

+0

文件仍然會請求體的一部分:HTTPS ://msdn.microsoft.com/en-us/library/microsoft.owin.staticfiles.staticfileoptions.onprepareresponse(v = vs.113).aspx#P:Microsoft.Owin.StaticFiles.StaticFileOptions.OnPrepareResponse – Valter

+0

這不工作。我已經添加了NuGet包和你的代碼,構建。但是,即使OwinContext.User爲空,** attachments **文件夾下的靜態文件仍然可以快速提供服務。有什麼想法嗎? – Nexus

0

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

這樣,服務器返回「未授權」所要求的文件,而不是。

+0

該文件仍將是請求正文的一部分:https://msdn.microsoft.com/en-us/library/microsoft.owin.staticfiles.staticfileoptions.onprepareresponse(v=vs.113).aspx#P:Microsoft .Owin.StaticFiles.StaticFileOptions.OnPrepareResponse – Valter

+0

@Valter Nope,我用代理進行了檢查,在這種情況下,它不是 – Darxis

+0

當我看着firefox/chrome上的開發人員工具時,我看到文件(位)附加到主體未經授權之後。 – Valter

相關問題