01.protected void btnLogin_Click(object sender, EventArgs e)
02.{
03. // Extract domain name from provided DomainUsername e.g Domainname\Username
04. string domainName = GetDomainName(txtUserName.Text);
05. // Extract user name from provided DomainUsername e.g Domainname\Username
06. string userName = GetUsername(txtUserName.Text);
07. IntPtr token = IntPtr.Zero;08. //userName, domainName and Password parameters are very obvious.09. /* dwLogonType (3rd parameter): I used LOGON32_LOGON_INTERACTIVE, This logon type is
10. intended for users who will be interactively using the computer, such as a user being
11. logged on by a terminal server, remote shell, or similar process. This logon type has
12. the additional expense of caching logon information for disconnected operations. For
13. more details about this parameter please see http://msdn.microsoft.com/en-
14. us/library/aa378184(VS.85).aspx */15. /* dwLogonProvider (4th parameter) : I used LOGON32_PROVIDER_DEFAUL, This provider
16. uses the standard logon provider for the system. The default security provider is
17. negotiate, unless you pass NULL for the domain name and the user name is not in UPN
18. format. In this case, the default provider is NTLM. For more details about this
19. parameter please see http://msdn.microsoft.com/en-us/library/aa378184(VS.85).aspx */20. /* phToken (5th parameter): A pointer to a handle variable that receives a handle to
21. a token that represents the specified user. We can use this handler for impersonation
22. purpose. */
23. bool result = LogonUser(userName, domainName, txtPassword.Text, 2, 0, ref token);
24. if (result)
25. {
26. //If Sucessfully authenticated
27. /* When an unatuthenticated user try to visit any page of your application that is
28. only allowed to view by authenticated users then ASP.NET automatically redirect that
29. user to login form and add ReturnUrl query string parameter that contain the url of a
30. page that user want to visit, So that we can redirect the user to that page after
31. authenticated. FormsAuthentication.RedirectFromLoginPage() method not only redirect
32. the user to that page but also genrate an authentication token for that user. */
33. if (string.IsNullOrEmpty(Request.QueryString[“ReturnUrl”]))
34. {
35. FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
36. }37. /* If ReturnUrl query string parameter is not present , then we need to generate
38. authentication token and redirect the user to any page ( acording to your application
39. need). FormsAuthentication.SetAuthCookie() method will generate Authentication
40. token*/
41. else
42. {
43. FormsAuthentication.SetAuthCookie(txtUserName.Text, false);
44. Response.Redirect(“default.aspx”);
45. }
46. }
47. else
48. {
49. //If not authenticated then display an error message
50. Response.Write(“Invalid username or password.”);
51. }
52.}