Question

I am using a MS Access form with the below vba code for my startup page where the user enters a username and password where if its ok, he is forwarded to a dashboard page with relevant content. I was checking to see if the code is SQL Injection proof, and to my horror, it proceeded to log in without a single problem! Could anyone please assist me harden the code to prevent a sql injection attack?

If (Me.UserNameTextBox <> "" And Me.passwordtextbox <> "") Then    
        hook = """"
SQLCheckUser = ""
SQLCheckUser = SQLCheckUser & " SELECT Id, UserName, UserCode FROM UserTable"
SQLCheckUser = SQLCheckUser & " WHERE UserName = " & hook & me.UserNameTextBox.value & hook
SQLCheckUser = SQLCheckUser & " AND UserPassword = " & hook & me.passwordtextbox.value & hook
SQLCheckUser = SQLCheckUser & " AND IsInactive=0"

'Create RecordSet
   Set rst = CurrentDb.OpenRecordset(SQLCheckUser)

'Go to first record
    rst.MoveLast
    rst.MoveFirst

    If rst.RecordCount <> 1 Then
        MsgBox "Error 2: Please recheck your login details" 'Error 2 Cant find the user or too many users
        rst.Close
           Else
'Good LogIn, load the values of the record into rst   
    ID = rst.Fields("Id")
    UserName = rst.Fields("UserName")
    UserCode = rst.Fields("UserCode")
    IsLoggedIn = True
    rst.Close

     DoCmd.Close
     DoCmd.OpenForm ("Dashboard")

    End If
   Else
MsgBox "Please recheck your login details" ‘ Either UserName or Password has not been entered
End If
Was it helpful?

Solution

Parameterized queries are used to protect against SQL Injection vulnerabilities. In your case you would use something like this

Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.CreateQueryDef("", _
        "PARAMETERS prmUserName TEXT(255), prmUserPassword TEXT(255);" & _
        "SELECT Id, UserName, UserCode FROM UserTable" & _
        " WHERE UserName = [prmUserName] AND UserPassword = [prmUserPassword] AND IsInactive=0")
qdf!prmUserName = Me.UserNameTextBox.Value
qdf!prmUserPassword = Me.passwordtextbox.Value
Set rst = qdf.OpenRecordset
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top