ASP.NET: Build Your Own Security Framework with SetAuthCookie

All of ASP.NET's security/membership support boils down to generating a cookie that allows the user access to your site's folders.

I mentioned SetAuthCookie in a comprehensive look at the ASP.NET security framework about seven years ago, but it's worth mentioning again (primarily because I keep getting asked to solve this problem).

If you find that the ASP.NET Membership provider's security framework gives you too much of a solution -- if you want to authenticate users your own way -- you can. All of ASP.NET's security/membership support boils down to generating a cookie that allows the user access to your site's folders. You can generate that cookie from any process you care to create by using the FormsAuthentication class' SetAuthCookie method, passing the name of the user and a Boolean value.

This call to SetAuthCookie generates a cookie that says this user ("Peter") is authenticated:

FormsAuthentication.SetAuthCookie( "Peter",  False)

The second parameter specifies whether the cookie is an in-memory cookie (no expiry date) or a permanent cookie that will be saved on the user's hard disk. If you specify true in the second parameter, the user will be "permanently" authenticated for your site -- at least, as long as they come to your site from the computer on which the cookie is saved. You can also provide a third parameter as a path for the cookie if you don't want the cookie returned on every request for your site.

This method doesn't completely ignore the settings in your web.config file. If, for instance, you've set the cookieless attribute on the forms element to AutoDetect, ASP.NET will attempt to determine if the current client supports cookies (it reports that through the FormsAuthentication's CookieSupported property). If cookies aren't supported, the SetAuthCookie method ensures that the authentication information is put in the URL.

This method doesn't directly support roles, so you'll have to authorize access to your site's folders by user name rather than by role.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

Subscribe on YouTube