Forms Authentication - Manual Authentication

I’ve had several occasions in the past where I’ve needed to do my own authentication or I’ve needed to add some additional methods to the authentication process.

As easy as Microsoft has made the authentication process, you might think that in order to  manually authentication you’d need to write all of your authentication code manually.  But nothing could be further from the truth.

In fact, most of the time, all you need to do is trap an event handler in the existing login control.

A couple of years ago, I was asked to create a login page that used a web service to authenticate the user.  I also needed to add another form field to the login screen so it became obvious that to do this I’d need to turn the login control into a templated control.

Once this was done it was a simple matter to trap the click event of the login button, authenticate against the web service and then set the authentication cookie for ASP.NET.

Since I can’t show you how to authenticate against the service, your implementation will almost certainly be different, we will skip that section.  But to set the cookie, all we need to do is to revert to the ASP.NET 1.1 way of setting up the login.

if (Request.QueryString["ReturnUrl"] != null)
{
FormsAuthentication.RedirectFromLoginPage (m_tbUsername.Text, persistentCookie);
}
else
{
FormsAuthentication.SetAuthCookie (m_tbUsername.Text, persistentCookie);
Response.Redirect("~/");
}

The first line checks to see if there was a Return URL specified.  If there was we can use the RedirectFromLoginPage API.  Otherwise, we need to set the Authentication Cookie manually and redirect on our  own.

The persistentCookie parameter is true if we want the user to always be logged in.  Otherwise, the login is for the session.

 

References
0
Average: 3 (1 vote)

Dave Bush has been programming for 20 years. He currently blogs about .NET at http://blog.dmbcllc.com and provides .NET coaching to small and medium sized companies. Dave is a DZone MVB and is not an employee of DZone and has posted 20 posts at DZone.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

jbubriski replied on Tue, 2009/10/13 - 3:04pm

Hi Dave,

  Are there any server-side validation errors that you would need to catch?  I want to say that the asp:login control has some other error handling built in, that would not longer be there if it was converted to a templated control.  Thanks,

John

DaveMBush replied on Tue, 2009/11/10 - 10:02am in response to: jbubriski

When it is first converted to a template, it has all the controls it would have had as not a template.  So, unless you remove something, it should work the same in either mode.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.