Karl
Karl

Reputation: 53

Forms authentication ASP.NET webforms

I have an ASP.NET webforms application that uses forms authentication. For the pages that don't need authentication I have those in a separate folder. All other pages are in the main folder and use authentication. This all works.

The application now needs to serve images. So, if I have a url like https://mysite/{id} I look up an image in the database for the specified id and serve the image. To serve the image, I have code in a BeginRequest method in the global.asax. I check to see if the url is of type https://mysite/{id} and serve the image by doing a response.write and write the bytes of the image.

When I do the response.write the forms authentication kicks in and sends me to a login page.

So, for a url of https://mysite/{id}, I don't want to do forms authentication, but I don't know how to turn authentication off for this type of url without turning off authentication for pages I do want authentication for.

Is there a way to not do forms authentication in the BeginRequest method? Is there a property or method I can call in the BeginRequest to turn forms authentication off?

Upvotes: 0

Views: 345

Answers (1)

sep7696
sep7696

Reputation: 575

There are a couple ways :

1.(EASYONE)ACCORDING TO THIS DOC use the forms authentication configuration in web.config to exclude URLs. You can add an element with a path attribute for the URL pattern you want to exclude, and set enabled="false" on the element:

<location path="images/">
  <system.web>
    <authorization>
      <deny users="?" />
    </authorization>
  </system.web>
</location>

2.In your BeginRequest handler, check the requested URL and if it matches your excluded pattern, call HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(string.Empty), null); This will manually set an anonymous user principal before the forms auth module executes or u can Create a custom forms authentication module that overrides the default one, and in the OnAuthenticate method add logic to skip authentication based on the URL.

Upvotes: 1

Related Questions