简体   繁体   中英

Authorized File access in ASP.NET Web Application

Can some one please help me to get an idea on this? I have a C# website application in which I want to do authorization for accessing the documents in website directory.

If user requests for a document say pdf through a link in my website, http://www.mywebapp.com/documents/test.pdf , before opening the test.pdf in browser, I actually want to verify the user is authorized to access the pdf based on role he got. I have enabled forms authentication for the folder "documents" in IIS and system is redirecting to login page if user is not authenticated. I'm all good with that, but stuck with authorization.

I can't set the roles in web.config since it would different for different users. User role is stored in httpcookie for that particular user.

And in my documents folder there would be different documents targeted for different roles.

Say test.pdf for role called vendor. So only vendors can access this pdf

Another document form.pdf for role supplier- only users with role supplier can see this pdf .

Should I write some handler to execute before loading the pdf in browser? Or when ever requests comes as /documents/ should I have a URL rewrite to execute an aspx page to verify the authorization and if authorized display the page?

Can anybody please help me to get an idea on how to implement this authorization.

Appreciate your help!

Thanks, KK

Looks like your question is "how I can check cookie value on my page and return stream of a file with correct document type when cookie is ok".

  • make sure you are handling all request (much easier to do using MVC than WinForms, but possible in later too)
  • read and verify cookie
  • return file if check passed, don't forget to set "content-diposition" and "content-type" headers. Again File result in MVC is easier to use... Make sure to read file content under correct account if using impersonation.

You can add following code to web.config and try

<location path="documents/test.pdf ">
        <system.web>
                <authorization>
                        <allow roles="Vendors"/>
                        <deny users="*"/>
                </authorization>
        </system.web>
</location>

<location path="documents/form.pdf ">
        <system.web>
                <authorization>
                        <allow roles="Role Supplier"/>
                        <deny users="*"/>
                </authorization>
        </system.web>
</location>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM