Recommended hosting
Jul 04 2001

Securing pages with login scripts

Posted by admin under ASP

These functions can be used on certain pages you want password protected.

First create a file called includelogin.asp with this content:

<%
Response.Buffer = True


Function ValidateLogin( sId, sPwd ) 
	' For you to validate ID and PASSWORD
	' Maybe against a database
	' Here we have hardcoded some OK id:s and passwords
	'
	ValidateLogin = False

	If sId = "test" AND sPwd="secret" Then
		ValidateLogin = True
	End If
	If sId = "user2" AND sPwd="pwd2" Then
		ValidateLogin = True
	End If
End Function


Dim sText, fBack

fBack = False
If Request.Form("dologin") = "yes" Then 
	'Try to login
	If ValidateLogin( Request.Form("id"),Request.Form("pwd") ) = True Then
		'It is OK!!!
		'We are logged in so lets go back to the file that included us  
		fBack = True
		Session("logonid") = Request.Form("id")
	Else
		sText = "Wrong password or user id"
	End If
Else
	'We are not trying to login...
	If Session("loginid") <> "" Then 
		'
		fBack = True
		'We are logged in so lets go back to the file that included us  
	Else
		sText = "Please login"
	End If
End If

If fBack = False Then %>

	<html>

	<head>
	<meta http-equiv="Content-Language" content="en">
	<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
	<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
	<meta name="ProgId" content="FrontPage.Editor.Document">
	<title>You need to login</title>
	</head>

	<body>

	<%=sText%>	
	<%
	Dim sURL
	sURL = Request.ServerVariables("SCRIPT_NAME")
	If Request.ServerVariables("QUERY_STRING") <> "" Then
		'
		sURL = sURL & "?" & Request.ServerVariables("QUERY_STRING") 
	End If
	%>
	<form method="POST" action="<%=sURL%>">
	<input type="hidden" name="dologin" value="yes">
  	<table border="0" width="100%">
   	 <tr>
      <td>Loginname:</td>
      <td><input name="id" size="20"></td>
    </tr>
    <tr>
      <td>Password:</td>
      <td><input type="password" name="pwd" size="20"></td>
    </tr>
  </table>
  <p><input type="submit" value="Login" name="B1"></p>
	</form>

	</body>

	</html>
<%	
	Response.End
End If
%>


Then, in the file you want secured just include the file the first thing you do:

<!--#include file="includelogin.asp"-->


You could of course modify the includelogin.asp file so it looks a little nicer but that's up to you!

The secret here ( what makes it so easy to use ) is the use of Request.QueryString("SCRIPT_NAME") and Request.QueryString("QUERY_STRING"). This makes it work on any ASP code, even if you are calling it with parameters ( like test.asp?id=123 ).

When the right password is entered all those parameters will be transferred to the script as it should.