ASP.net Authentication on Generated Link - asp.net

One of our ASP web apps has a button, that generates a expiring link to a form. We have noticed that anyone with said link can view the form. I am researching a way to have the end-user be checked for authorization when the link is opened up. Ask them for their username/password before they can view the link.
my sub that generates the link:
Protected Sub ButtonLink_Click(sender As Object, e As EventArgs)
Dim strSQL As String = ""
Dim wapguid As String = ""
Dim cmd As New SqlCommand
wapguid = System.Guid.NewGuid().ToString("N")
strSQL = "INSERT INTO [WapCustomerAccess] (wapid, wapguid, expires, generatedBy) values (#wapid, #wapguid, #expires, #generatedBy)"
cmd.CommandType = CommandType.Text
cmd.CommandText = strSQL
cmd.Parameters.AddWithValue("#wapid", WAPID)
cmd.Parameters.AddWithValue("#1", wapguid)
cmd.Parameters.AddWithValue("#generatedBy", Session.Item("UserFullName"))
cmd.Parameters.AddWithValue("#expires", Date.Now.AddDays(31).ToString)
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("cnnCFHSWAP").ConnectionString
Dim con As New SqlConnection(strConnString)
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message & "<br />")
Finally
con.Close()
con.Dispose()
End Try
Dim t As New TextBox()
t.Text = "http://wap-test.cfhs.local/secure/waplink.aspx?SSL=true&hash=" & WAPID & "&guid=" & wapguid & "&expires=45&suid=05A2FF&salt=x00FF&enc=true"
t.ID = "txtLink"
t.Width = 800
t.ReadOnly = True
t.BackColor = Drawing.Color.SeaShell
PanelLink.Visible = True
PanelLink.Controls.AddAt(0, t)
PanelLink.Controls.Add(New LiteralControl("<br />"))
End Sub

You will need to restrict access to waplink.aspx in the app that is referred to in your generated links. Depending on that app, you will find suitable tutorials for setting up authentication/authorization, like [1].
[1] https://weblogs.asp.net/gurusarkar/setting-authorization-rules-for-a-particular-page-or-folder-in-web-config

Related

Asp.net multible table access vb.net

and good day..
I have a code of asp.net in vb.net and work fine for one table but i need to add multible table of( master and dr ) to code the data is the sum from the two table but its different. can anyone help me..thanks advance for all
Private Sub getData(ByVal user As String)
Dim dt As New DataTable()
Dim connectionString As String
Dim connection As OleDbConnection
connectionString = ConfigurationManager.ConnectionStrings("Data_For_netConnectionString").ToString
connection = New OleDbConnection(connectionString)
connection.Open()
Dim sqlCmd As New OleDbCommand("SELECT * from master WHERE UserID = #user", connection)
sqlCmd.CommandText = _
"SELECT name, manistry, university, send, card FROM master "
Dim sqlDa As New OleDbDataAdapter(sqlCmd)
sqlCmd.Parameters.AddWithValue("#user", user)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
TextBox1.Text = dt.Rows(0)("manistry").ToString
TextBox2.Text = dt.Rows(0)("university").ToString
TextBox4.Text = dt.Rows(0)("send").ToString
TextBox21.Text = dt.Rows(0)("card").ToString
name.Text = dt.Rows(0)("name").ToString
End If
connection.Close()
End Sub

How can i populate a DropDownList based on BasicDatePicker selection in ASP

I have an asp.net web form application to bind data (REFERENCE_NO) to a DropDownList (ddlRef) .ddlRef retrieves data from a MySql database based on the selected date in a BasicDatePickerControl (bdpApps) . My code is as below:
Protected Sub loadRefnumbers()
Try
cmd = New MySqlCommand("select idapp,REFERENCE_NO from ONLINELOANS where APPLICATION_DATE ='" & DateFormat.getSaveDate(bdpApps.SelectedDate) & "'", con)
adp = New MySqlDataAdapter(cmd)
Dim ds As New DataSet
ds.Clear()
adp.Fill(ds, "DATE_REFS")
If ds.Tables(0).Rows.Count > 0 Then
ddlRef.DataSource = cmd.ExecuteReader()
ddlRef.DataTextField = "REFERENCE_NO"
ddlRef.DataValueField = "idapp"
ddlRef.DataBind()
Else
ddlRef.DataSource = Nothing
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I have a getSaveDate function that converts the date format in the basicdatepicker control to the MySql Date format (YYYY-MM-DD). When i debug the app the ddlRef control is not updating to reflect the values from REFERENCE_NO column. Is there anything wrong with my SQL command?
Solution for question above.For those who use BasicDatePicker 1_4_3 in asp.net webforms the code for my problem is to call the query on the SelectionChanged handler for the datepicker control:
Protected Sub bdpApps_SelectionChanged(sender As Object, e As EventArgs) Handles bdpApps.SelectionChanged
con = New SqlConnection(ConfigurationManager.ConnectionStrings("constr").ConnectionString)
Using cmd As New SqlCommand("SELECT id,REFERENCE_NO from ONLINELOANS where APP_DATE='" & DateFormat.getSaveDate(bdpApps.SelectedDate) & "'")
cmd.CommandType = CommandType.Text
cmd.Connection = con
con.Open()
ddlRef.DataSource = cmd.ExecuteReader()
ddlRef.DataTextField = "REFERENCE_NO"
ddlRef.DataValueField = "idapp"
ddlRef.DataBind()
ddlRef.Items.Insert(0, New ListItem("--SELECT--", "0"))
ddlRef.SelectedIndex = 0
con.Close()
End Using
End Sub

Needs to retrieve data first and then update the new entry into DB

I need to retrieve data from the database first and then update the table with the new entry, following is my code but I am having an error:
"Invalid attempt to call Read when reader is closed."
I know I need to open the datareader by commenting dr1.close, but as soon as I did that I face an another exception:
"there is already an open datareader associated with this command which must be closed first. vb.net"
Imports System.IO
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Data
Partial Class Officer_Module_GST_id_password
Inherits System.Web.UI.Page
Dim sscript As String
Dim sms As New smsgw
Dim mail As New MailSender
Dim cmd As New SqlCommand
Dim ds As New DataSet
Dim dr As SqlDataReader
Dim objconn As New connectioncls
Dim name As String
Dim pid As String
Dim pwd As String
Dim email_sent As Integer
Dim email_status As String
Dim mobile As String
Dim message As String
Dim subject As String
Dim email As String
Dim mtext As String
Protected Sub validatedeal_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles validatedeal.Click
containertwo.Visible = True
txt_subject.Text = "Communication of the Provisional Identification Number and Password"
txt_mail.Text = "Instance mail"
End Sub
Protected Sub btnsendmail_Click(ByVal sender As Object, ByVal e As System.EventArgs)
objconn.openconn()
cmd.Connection = objconn.conn
cmd.CommandText = "Select Trade_name,provissional_id,access_token,reg_mobile_no,reg_email_id,email_status,isnull(no_of_email_sent,0) from Provisional_details"
Dim dr1 As SqlDataReader = cmd.ExecuteReader()
While (dr1.Read())
name = dr1(0).ToString()
pid = dr1(1).ToString()
pwd = dr1(2).ToString()
mobile = dr1(3).ToString()
email = dr1(4).ToString()
email_status = dr1(5).ToString()
email_sent = dr1(6).ToString()
subject = "subject to instance"
mtext = "new instance email"
message = "new instance message"
Try
MailSender.SendEmail("riteshbhatt93" + "#gmail.com", "rock_on", email, subject, mtext, System.Web.Mail.MailFormat.Text, "")
Try
Call sms.SendSMSUsingNICGW(mobile, message)
Catch
sscript = "<script language=javascript>alert('Message not sent!!')</script>"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", sscript)
sscript = Nothing
Exit Try
Finally
End Try
Try
Call sms.SendSMSUsingMGOVGW(mobile, message)
Catch
sscript = "<script language=javascript>alert('Message not sent!!')</script>"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", sscript)
sscript = Nothing
Exit Try
Finally
End Try
Catch
Dim cmd1 As New SqlCommand
cmd1.Connection = objconn.conn
cmd1.Parameters.AddWithValue("#mobile", mobile)
cmd1.Parameters.AddWithValue("#Email_status", "NO")
cmd1.CommandText = "Update Provisional_details set Email_sent = #Email_status where reg_mob_no = #mobile"
cmd1.ExecuteNonQuery()
cmd1.Parameters.Clear()
Exit Sub
Finally
End Try
dr1.Close()
Dim cmd2 As New SqlCommand
cmd2.Connection = objconn.conn
cmd2.Parameters.AddWithValue("#mobile", mobile)
cmd2.Parameters.AddWithValue("#Email_status", "YES")
cmd2.Parameters.AddWithValue("#emailsent", email_sent + 1)
cmd2.CommandText = "Update Provisional_details set email_status = #Email_status,no_of_email_sent = #emailsent where reg_mobile_no = #mobile"
cmd2.ExecuteNonQuery()
cmd2.Parameters.Clear()
End While
sscript = "<script language=javascript>alert('Your Mail has been sent to all applied dealers!!')</script>"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", sscript)
sscript = Nothing
End Sub
End Class
I've pared this down to just the method that matters (like you should have done when posting the question). Updates are in the method, using comments to annotate what's going on.
Protected Sub btnsendmail_Click(ByVal sender As Object, ByVal e As System.EventArgs)
'Best practice in .Net is use a brand new connection instance for most DB calls. Really.
'Don't try to be clever and re-use one connection. Just use the same string.
Dim connString As String = "Connection String Here"
'Using block will guarantee connection closes properly, even if an exception is thrown
Using cn As New SqlConnection(connString), _
cmd As New SqlCommand("Select Trade_name,provissional_id,access_token,reg_mobile_no,reg_email_id,email_status,isnull(no_of_email_sent,0) from Provisional_details", cn), _
cn2 As New SqlConnection(connString), _
cmd2 As New SqlCommand("Update Provisional_details set email_status = #Email_status,no_of_email_sent = #emailsent where reg_mobile_no = #mobile", cn2)
'Define your parameters as early as possible, and be explicit about parameter types and lengths
' This will avoid potentially crippling performance gotchas
cmd2.Parameters.Add("#mobile", SqlDbType.NVarChar, 14)
cmd2.Parameters.Add("#Email_status", SqlDbType.VarChar, 5)
cmd2.Parameters.Add("#emailsent", SqlDbType.Int)
'Separate SQL statements in a tight loop like this is one of the few places to re-use a connection object...
' Even here, it should be a BIG RED FLAG that there's a better way to handle this whole process that avoids multiple calls to the DB.
' For example, it might be better to assume success, Update the DB accordingly in the original statement, and then only write failures back when needed
cn2.Open()
cn.Open()
dr1 As SqlDataReader = cmd.ExecuteReader()
While (dr1.Read())
'Best practice in .Net are to declare these variables in the method where you use them
Dim name As String = dr1(0).ToString()
Dim pid As String = dr1(1).ToString()
Dim pwd As String = dr1(2).ToString() 'You're not really storing passwords in plain-text are you? Please say, "No".
Dim mobile As String = dr1(3).ToString()
Dim email As String = dr1(4).ToString()
Dim email_status As String = dr1(5).ToString()
Dim email_sent As Integer = dr1.GetInt32(6) 'It's a number. You do math on it later. Get the INTEGER value
Dim subject As String = "subject to instance"
Dim mtext As String = "new instance email"
Dim message As String = "new instance message"
cmd2.Parameters("#mobile").Value = mobile
Try
MailSender.SendEmail("riteshbhatt93" + "#gmail.com", "rock_on", email, subject, mtext, System.Web.Mail.MailFormat.Text, "")
Try
' Also... the "Call" keyword is a vb6-era relic that has no purpose any more. Don't use it
sms.SendSMSUsingMGOVGW(mobile, message)
Catch
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", "<script language=javascript>alert('Message not sent!!')</script>")
'Don't set values to "Nothing" to free them in VB.Net.
'It doesn't help the way it used to in vb6/vbscript, and can actually be HARMFUL in rare cases in .Net
End Try
' Do you really mean to try both gateways, even if the first succeeds?
' Because that's what the original code is doing.
Try
sms.SendSMSUsingNICGW(mobile, message)
Catch
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Empty", "<script language=javascript>alert('Message not sent!!')</script>")
'No need to call Exit Try here,
' and no need for an empty Finally section
End Try
Catch
cmd2.Parameters("#emailsent") = email_sent
cmd2.Parameters("#Email_status") = "NO"
cmd2.ExecuteNonQuery()
End Try
cmd2.Parameters("#Email_status").Value = "YES"
cmd2.Parameters("#emailsent").Value = email_sent + 1
cmd2.ExecuteNonQuery()
End While
End Using
End Sub

Login page not working in vb asp.net

I am having an issue with my login page. I am not getting any errors so am not able to know where the problem is?
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Login.Click
'connection string
Dim mysqlconn As MySqlConnection = New MySqlConnection("server=localhost;user id=root;Password=123;database=users;persist security info=False")
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim mydata As New DataTable
Dim reader As MySqlDataReader
Try
mysqlconn.Open()
Dim query As String
query = "SELECT * FROM login_form where Username = '" & rfvUser.Text & "' and Password='" & rfvPWD.Text & "'"
cmd = New MySqlCommand(query, mysqlconn)
reader = cmd.ExecuteReader
While reader.Read()
If rfvUser.Text = "admin" And rfvPWD.Text = "admin" Then
Me.Session("User") = Me.rfvUser.Text
Server.Transfer("Admin.aspx")
ElseIf (rfvUser.Text = reader("UserName").ToString()) And (rfvPWD.Text = reader("Password").ToString()) Then
Me.Session("User") = Me.rfvUser.Text
Server.Transfer("Ersal_send.aspx")
Else
ClientScript.RegisterStartupScript(Page.[GetType](), "validation", "<script language='javascript'>alert('Invalid Username or Password')</script>")
reader.Close()
End If
End While
Catch ex As Exception
MsgBox(ex.Message)
Finally
mysqlconn.Dispose()
End Try
End Sub
End Class
Have you tried running the query directly via a SQL client? If your query is not returning any rows, then your procedure will simply exit without any errors as it will never enter the While loop.
Another advice: It is never a good idea to pass user input directly into a query. This leads to SQL injection. Use parameterised queries. Google for it.

Session ASP.NET doesnt seem to work

I have the following code on my default.aspx
Label1.Text = Session("valueName").ToString()
And the following code on my login.aspx
Dim strCon As String = ConfigurationManager.ConnectionStrings("Goed").ConnectionString
'Create Connection String And SQL Statement
Dim strSelect As String = "SELECT COUNT(*) FROM tbl_LogIn WHERE Gebruiker = #Gebruiker AND Wachtwoord = #Wachtwoord"
Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = strSelect
Dim Gebruiker As New SqlParameter("#Gebruiker", _
SqlDbType.VarChar)
Gebruiker.Value = TxtUs.Text.Trim().ToString()
cmd.Parameters.Add(Gebruiker)
Dim Wachtwoord As New SqlParameter("#Wachtwoord", _
SqlDbType.VarChar)
Wachtwoord.Value = TxtPw.Text.Trim().ToString()
cmd.Parameters.Add(Wachtwoord)
con.Open()
Dim result As Integer = DirectCast(cmd.ExecuteScalar(), Int32)
con.Close()
If result >= 1 Then
Response.Redirect("default.aspx")
Session("valueName") = TxtUs.Text.ToString()
Else
lblMsg.Text = "Gebruikers naam en of wachtwoord kloppen niet"
End If
End Sub
But it doesnt seem to help. I don't get any error or whatso ever, any idea?
The Redirect method ends the execution, so you have to set the session variable before redirecting:
Session("valueName") = TxtUs.Text.ToString()
Response.Redirect("default.aspx")
you are redirecting before setting the session. you should first set the session and then redirect the page.
Or
Your result variable is not 1 or bigger than 1. you should check that too

Resources