ASP.NET Secrets, Part 3, Page 2
How to Authenticate Just Part of Your Site
Sometimes you don't want to authenticate all of your Web application. There are situations where you just want to keep a couple of pages, such as a basket checkout form, available only to those authorized users.
Yes, you could try doing it manually by remembering some sort of session variable and/or using cookies. But a much neater solution is to use a little-known trick that allows you to still use ASP.NET Forms authentication, but only with an exclusive number of pages on your site.
- Alter your Web.config file, so it uses Forms authentication. You can do this by either following step one in the "Four Steps to ASP.NET Authentication" tip (if you're using Web.config to store the users), or simply change the <authentication> element to <authentication mode="Forms" /> (if you're going to authenticate using your own database, or similar). This time, however, we're not going to deny regular, unauthenticated visitors.
- Still in your Web.config file, just underneath the <configuration> element, add the following, replacing "checkout.aspx" with the page you want to protect. This will ensure ASP.NET denies access to any unauthenticated users attempting to view this page. You can add as many <location> blocks as you wish and can include file names and folders in the path:
<location path="checkout.aspx"> <system.web> <authorization> <deny users="?" /> </authorization> </system.web> </location>
- Go ahead and create your login.aspx page as you did in the last tip.
And that's it! You've created a Web application that uses Forms authentication. However, by default it grants access to all users. You've then added a clause in Web.config that states all those attempting to view checkout.aspx must be authorized first—and are therefore redirected to login.aspx when unauthorized surfers access the page.
Note that this change to the Web.config file is the only real difference to the authentication process here. The other methods of logging out, retrieving the username, and so on, all work in exactly the same way as with full authentication.