Welcome to the third part of ASP.NET Secrets!
I’m Karl Moore and today, once again, we’re exploring even more chunks of code to put your Web applications into sixth gear. In this article, we’ll check out:
- Four Steps to ASP.NET Authentication
- How to Authenticate Just Part of Your Site
- The Best Place to Store Your Settings
- Steal Fantastic Forum Code from Microsoft and Save Yourself Hours!
And they’ve all been inspired by the mass of tips, tricks, and little-known .NET techniques shared in my latest book, VB.NET and ASP.NET Secrets. Make sure you pick up your copy—it makes a great reference tool.
Plus, fancy contributing to this series? I’d love to hear all about your favorite .NET tips and tricks. Simply send them to me—firstname.lastname@example.org—and I’ll publish the best, full credit given.
But enough of that. And more of this… the secrets!
Four Steps to ASP.NET Authentication
If you’ve created a Web application in Visual Studio .NET, you should be aware that, by default, anyone can access your pages. However, there is a way to keep nosy, unwanted types out—by using authentication.
ASP.NET includes support for three core types of authentication: Windows, which only allows certain Windows accounts access to a page; Passport, which uses the Microsoft Passport universal login system to verify a user; and Forms, the most popular method of authentication, which we’ll be covering here.
When a user attempts to access a page that uses Forms authentication, they get redirected to a login screen. From here, your surfer can provide a username and password. You then validate the credentials and grant or deny access to your pages accordingly.
Want to set up ASP.NET Forms authentication? Just follow my five quick and easy steps:
- Open the Web.config file in your Solution. This stores a number of settings for your Web application. Edit the <authentication> elements, so it reads something like the following (alter usernames and passwords as appropriate—and watch both your casing and spacing). This provides your application with a list of valid users:
<authentication mode="Forms"> <forms> <credentials passwordFormat="Clear"> <user name="test1" password="password" /> <user name="test2" password="password" /> </credentials> </forms> </authentication>
- Still in the Web.config file, remove the <allow users=”*” /> line from within the <authorization> element. This line grants access to anyone—and we’ve just erased it.
- Still within the <authorization> element, add the following line to deny access to all unknown users (that is, those not authenticated):
<deny users="?" />
- Create a page called “login.aspx”. By default, all unauthenticated users will be redirected to this page. Add TextBox controls (txtUsername and txtPassword) for your browser to supply credentials. Also, add a CheckBox (chkPersist) to be used if the user wants their machine to automatically log them in next time.
- Behind a Login button on your login.aspx page, add code similar to the following to authenticate your user:
If System.Web.Security.FormsAuthentication.Authenticate( _ txtUsername.Text, txtPassword.Text) = True Then System.Web.Security.FormsAuthentication.Redirect _ FromLoginPage( _ txtUsername.Text, chkPersist.Checked) Else Response.Write("Invalid credentials - go back and try _ again!") End If
And that’s it! Now, whenever a user visits a page in your application—and they’re unauthenticated—they’ll be redirected to login.aspx. From there, they’ll be able to provide credentials. The .Authenticate method attempts to match these with a valid username and password combination in Web.config. If the credentials are invalid, a generic error message is displayed. If everything is fine, the .RedirectFromLoginPage method runs, taking the username and whether the login ‘persists’ (ie, is remembered by the computer between sessions) as arguments, then sends the user back to their initially requested page.
After this, whenever you need to refer back to the username, simply check out the User.Identity.Name property. And when the user requests to explicitly log out, run code similar to the following:
Top Tip: If you don’t want to use login.aspx as your login form, you can change the page by adding a loginUrl attribute to the <forms> element of your Web.config file. For example, the following tag makes myloginpage.aspx the default login page: <forms loginUrl=”myloginpage.aspx” />.
Caption: Authentication kicking in as I tried to access a restricted page
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.
The Best Place to Store Your Settings
Many Web developers end up storing important pieces of data—database connection strings, passwords, default settings—as troublesome constants. The problem with this is that they’re difficult to edit: The slightest of changes means a complete recompile.
However, with ASP.NET, there is an easier way. It’s likely you’re well aware of the Web.config file, which stores settings for your applications, such as the session state timeout and authentication mode. It can also hold your own settings.
How? It’s easy. Simply add your own personal settings to the Web.config file, like this:
<configuration> ... <appSettings> <add key="serverName" value="diomedes" /> </appSettings> ... <system.web> ... </system.web> </configuration>
Here, I’ve added a key called “serverName” containing a value of “diomedes”. You can list as many values here as you like: just keep adding <add> elements. And how do you read the value in your code? Simply reference the AppSettings collection of the System.Configuration.ConfigurationSettings class, as so:
x = System.Configuration.ConfigurationSettings.AppSettings _ ("serverName")
And don’t forget: Web.config is just an XML file and easily editable without a recompile. You could even use a third-party control, such as the free Web.config Editor from Hunterstone, to simplify all your administration. Easy!
Steal Fantastic Forum Code from Microsoft and Save Yourself Hours!
I’ve always found bulletin boards to be the easiest method of generating visitor loyalty at a site. The trouble is, the very best ones always take an absolute age to build. But who mentioned doing it yourself?
Back in July 2001, ASP author Scott Mitchell decided to create his own bulletin board as a pet .NET project. Within months, Microsoft had stepped onto the scene as adopted it as their very own online ASP.NET forum—which you can find online at www.asp.net.
Well, after months of new features and major tweaking, our favorite software giant has quietly unveiled the full source code for download at www.asp.net/Forums/Download—and for free, too!
At the time of this writing, the code release was still in well-developed beta mode; however, there are big plans to release the absolute final version over the coming months.
It’s only a quick tip, but it could save you hours!
Caption: Have all this forum functionality, in seconds!
Coming Up in Part Four of ASP.NET Secrets:
- Create Super Fast ASP.NET Applications, with Caching
- Hiding Error Code from Your Clients
- Forget 404: Customizing Your Page Not Found
- Ten Steps to Successful Debugging
See you next time!
About the Author
Karl Moore is a technology author living in Yorkshire, England. He runs his own consultancy group, White Cliff Computing Ltd, and is author of two best-selling books exposing the secrets behind Visual Basic .NET. When he’s not writing for magazines, speaking at conferences, or making embarrassing mistakes on live radio, Karl enjoys a complete lack of a social life. Check out Karl’s newest book, Ultimate VB .NET and ASP.NET Code Book.
# # #