My login control isn't working as intended anymore. It pulls the username and password from a database and then redirects the user to Home.aspx. Redirecting sadly doesn't happen. It does add this to the end of the url, but nothing happens
ReturnUrl=%2fHome.aspx
This is the shortend ASP code
<asp:Login ID="Login1" runat="server" OnAuthenticate= "ValidateUser"
DestinationPageUrl="~/Home.aspx"> </asp:Login>
Plus .cs code
protected void ValidateUser(object sender, AuthenticateEventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB_CONNE"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Username =#Username and Password=#Password", con);
cmd.Parameters.AddWithValue("#Username", Login1.UserName);
cmd.Parameters.AddWithValue("#Wachtwoord", Login1.Password);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
Session["Uname"] = Login1.UserName;
if (dt.Rows.Count > 0)
{
Response.Redirect("Home.aspx");
}
I have been working on functionality in which not logged in users cant acces certain pages, but I'm not sure if that's the thing that's screwing it up..
After fiddling a little I noticed deny users seems to have an effect on it, but don't know any other way to be redirecting non-login attempts.
Any help would be greatly appreciated!
Looking at your code, in sql command your query have password parameter defined as #Password while adding it to the cmd parameters collection you have #Wachtwoord instead of the #Password.
Here is the updated code:
SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Username =#Username and Password=#Password", con);
cmd.Parameters.AddWithValue("#Username", Login1.UserName);
cmd.Parameters.AddWithValue("#Password", Login1.Password);
Also, instead of always redirecting to Home.aspx you can get the return url using FormsAuthentication.GetRedirectUrl. So if you try to access some page Protected.aspx without logging in the user will be redirected to Login.aspx?ReturnUrl=protected.aspx and after login user will be redirected to Protected.aspx page.
if (dt.Rows.Count > 0)
{
Response.Redirect(FormsAuthentication.GetRedirectUrl( Login1.UserName, false));
}
Related
I am working with asp.net and MSSQL server for development of online application, I like to add roles and Membership in website, membership and roles are stored in SQL Server, I tried and successes for login with SQL Users and while i change the code for restricted access for specific role the role is not listing on page.
my code for page are like below:
For Login
Dim userId As Integer = 0
Dim roles As String = String.Empty
Dim constr As String = ConfigurationManager.ConnectionStrings("InfinitudeConnectionString").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("Validate_User")
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#Username", Username.Text)
cmd.Parameters.AddWithValue("#Password", Password.Text)
cmd.Connection = con
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
reader.Read()
userId = Convert.ToInt32(reader("UserId"))
roles = reader("Roles").ToString()
con.Close()
End Using
con.Close()
End Using
Select Case userId
Case -1
errorText.Visible = True
errorText.Text = "Username and/or password is incorrect."
Exit Select
Case Else
Dim ticket As New FormsAuthenticationTicket(1, Username.Text, DateTime.Now, DateTime.Now.AddMinutes(1), True, roles,
FormsAuthentication.FormsCookiePath)
Dim hash As String = FormsAuthentication.Encrypt(ticket)
Dim cookie As New HttpCookie(FormsAuthentication.FormsCookieName, hash)
If ticket.IsPersistent Then
cookie.Expires = ticket.Expiration
End If
Response.Cookies.Add(cookie)
Session("login") = Username.Text
Response.Redirect(FormsAuthentication.GetRedirectUrl(Username.Text, True))
Exit Select
End Select
After that Master Page for Code :
Page Load
If Not Me.Page.User.Identity.IsAuthenticated Then
Response.Redirect(FormsAuthentication.LoginUrl)
ElseIf Session("login") = Nothing Then
FormsAuthentication.SignOut()
Session.Abandon()
Session.RemoveAll()
FormsAuthentication.RedirectToLoginPage("~/default")
Else
Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("InfinitudeConnectionString").ConnectionString)
Using cmd As SqlCommand = New SqlCommand
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "select hashtable.Username, lastlogin, hashtable.HASHid, hashtable.compID, company_list.Company_Name from hashtable inner join company_list on company_list.CompanyID = hashtable.CompID where hashtable.username = '" + Session("login") + "'"
Dim dt As New DataTable()
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
dt.Load(reader)
userID.Text = "Welcome Mr. " + dt.Rows(0).Item("Username").ToString.Trim()
LastLogin.Text = dt.Rows(0).Item("lastlogin").ToString.Trim()
Session("Companydetl") = dt.Rows(0).Item("compID").ToString.Trim()
Session("lastused") = dt.Rows(0).Item("HASHid").ToString.Trim()
con.Close()
End Using
End Using
End If
Global.ASAX
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
If HttpContext.Current.User IsNot Nothing Then
If HttpContext.Current.User.Identity.IsAuthenticated Then
If TypeOf HttpContext.Current.User.Identity Is FormsIdentity Then
Dim id As FormsIdentity = DirectCast(HttpContext.Current.User.Identity, FormsIdentity)
Dim ticket As FormsAuthenticationTicket = id.Ticket
Dim userData As String = ticket.UserData
Dim roles As String() = userData.Split(",")
HttpContext.Current.User = New GenericPrincipal(id, roles)
End If
End If
End If
End Sub
when I run below code the menu is not visible.
<% if (HttpContext.Current.User.IsInRole("Atul")) Then %>
Update Company Details
<% end if %>
and when I try to know the role of the current user it display blank.
please help
First up, you should always use parameters WHEN dealing with user input. You can get away using string concatenation for internal code, but when input comes from the web page, you REALLY want to use parameters.
So, for example, your code snip should be this:
Also, note that a sql command object has a connection, has a reader.
So LITTLE need to code over and over a seperate conneciton object and a reader - you do NOT need those - they eixst as part of the sqlcommand object.
eg this:
Dim strSQL As String
strSQL = "select hashtable.Username, lastlogin, hashtable.HASHid, hashtable.compID, company_list.Company_Name from hashtable " &
"inner join company_list on company_list.CompanyID = hashtable.CompID " &
"WHERE hashtable.username = #Login"
Using cmd As SqlCommand = New SqlCommand(strSQL,
New SqlConnection(ConfigurationManager.ConnectionStrings("InfinitudeConnectionString").ConnectionString))
cmd.Parameters.Add("#Login", SqlDbType.NVarChar).Value = Session("login")
Dim dt As New DataTable()
cmd.Connection.Open()
dt.Load(cmd.ExecuteReader)
With dt.Rows(0)
userID.Text = "Welcome Mr. " + .Item("Username")
LastLogin.Text = .Item("lastlogin")
Session("Companydetl") = .Item("compID")
Session("lastused") = .Item("HASHid")
End With
End Using
So, note how I don't need a separate connection object, and I don't need a reader (they already exist as part of the sql command object. So, just trying to save your keyboard here!!
Next up:
To test/check for role membership? If you setup security tables correctly, then you should have something like this:
You REALLY want to ensure that your tables follow the standard asp.net security.
Now in above, my main contact table is custom, but the rest of the tables are the standard ones required and generated by running the sql scripts to setup security. The REASON why this is a HUGE deal? Then you can secuire ANY web page by simply dropping in and haveing a web.config file in any sub folder, and thus you can secure any web page AUTOMATIC without code based on the users role.
So, you can say use this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<authorization>
<allow roles="PortalMaster" />
<deny users="*" />
</authorization>
</system.web>
</configuration>
So now, any user to use any page in that sub folder with the above web config? They MUST be a member of PortalMaster - they can't even load that page if they try to - no code required.
And if you done this correct, to test for role membership, then you can and should use this:
If Roles.IsUserInRole("PortalMaster") then
' code goes here for user role = PortalMaster
End if
So you can and should be able to use Roles.IsUserInRole("some role name")
Dim roles As String() = userData.Split(",")
Above is a bad idea - the roles need to come from the Web_usersInRoles table.
If you need to display all roles for a given user, then you can do this:
Say we have a simple button + text box:
<br />
<asp:Button ID="Button1" runat="server" Height="34px" Text="Button" Width="170px" />
<br />
<asp:TextBox ID="TextBox1" runat="server" Height="188px" TextMode="MultiLine" Width="423px"></asp:TextBox>
The button code can be this:
For Each MyRole As String In Roles.GetRolesForUser()
TextBox1.Text &= MyRole & vbCrLf
Next
result:
And with this setup, then in say the master page, you can control/set/hide menu bar items like this:
<li id="mAdmin" runat="server" class="dropdown" ClientIDMode="Static">
so above is a menu bar - master page. With roles, we can now do this:
Me.mAdmin.Visible = Roles.IsUserInRole("SiteAdmin")
So, to run security on that site - you really - but really really really want to use and have the membership role tables setup correctly here.
So to test for membership in a role you can and should be able to use
Roles.IsUserInRole("some role name here") = true/false
I'm creating a register page . When I write connection string to connect to SQL Server 2014 , this error is shown: Error Pic
protected void btnsignup_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=(local);DataBase=MyDataBase;integrated security=True");
SqlCommand cmd = new SqlCommand("insert into Users (Username,UPassword,Uname,UEmail) values ('"+ tbUname.Text + ","+ tbPass.Text + ","+tbname.Text +","+ tbemail.Text +"')");
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Like the error message shows you cannot login as that user (IIS/defaultapppool) on SQL server.
Ususally this happens if:
User does not exist
User does not have the permissions to access the database
Go to your SQL server management studio and make or edit your user. right click the security folder to make a new user, and make sure he is databaseReader, -Editor and/or databaseAdmin
You can also specify another user in your connectionstring by adding: User ID=name;Password=password
I want to view my account page after login in Textbox for updating, here is my code
SqlCommand cmd = new SqlCommand("SP_SelectUser",con);
con.Open();
cmd.CommandText = "SP_SelectUser";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#id", id);
int id = Convert.ToInt32(td.Rows[0]["id"]);
cmd.Parameters.AddWithValue("#id", "");
SqlDataReader dr = cmd.ExecuteReader();
td.Load(dr);
}
dr.Close();
name.Text = td.Rows[0]["name"].ToString();
emailid.Text = td.Rows[0]["emailid"].ToString();
passwd.Text = td.Rows[0]["Passwd"].ToString();
mobile.Text = td.Rows[0]["Mobile"].ToString();
First of all, your posted code is still not correct enough to make it clear what exactly your problem is.
For displaying a page from another page, you can use one of these options :
Response.Redirect("yourPage.aspx", false);
OR
Server.Transfer("yourPage.aspx", true);
You have to use either of these at the point in your code where you want to change the page from one to another.
Hope this helps.
On my Homepage i made i Visual Studio i want to have some welcome text on my firstpage.
The Thing is that i want in the middle of the text present some values that i grab from my db with a select query.
Lets say for example:
Welcome to my Homepage!
Currently there are (Select Count(UserID) FROM users where Status = 'active') Users active on my page and (Select Count(UserID) FROM users where Status = 'inactive') that are inactive.
Im really new to this but somehow i Need to run the my questions on Page_load and then be able to take that value and present it in a Label or something?
Thanks for your help
Using ADO.NET:
1: Create a connection object, set it's connection string property
2: Create a command object and set its text property to
Select Count(UserID) FROM users where Status = 'active'
3: Use ExecuteScalar method of the command object to find the result you want and set the label text property equal to that result.
Procedure
create procedure select
#activity
as
Begin
Select Count(UserID) FROM users where Status = #activity
end
C# Page Load
string activity1="active";
string activity2="Inactive";
sqlconnection con=new sqlconnection("give your connection string");
sqlcommand cmd=new sqlcommand();
cmd=new sqlcommand("select",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#activity",activity1);
String result1=cmd.ExecuteNonQuery();
sqlcommand cmd1=new sqlcommand();
cmd1=new sqlcommand("select",con);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#activity",activity2);
String result2=cmd.ExecuteNonQuery();
Label1.Text=result1;
Label2.Text=result2;
.aspx page
Welcome to my HomePage
Currently there are <asp:label id="Label1" runat="server"></asp:Label> Users active on my page and <asp:label id="Label2" runat="server"></asp:Label> that are inactive.
If you find this as useful and it solved your issue mark it as answer and give upvote.
Try this
if (!IsPostBack)
{
SqlConnection con = new SqlConnection(#"MY CONNECTION");
SqlCommand com = new SqlCommand("Select Count(UserID) FROM users where Status = 'active'", con);
SqlDataReader dr;
con.Open();
while (dr.Read())
{
Debug.WriteLine(dr[0].ToString());
}
con.Close();
}
My scenario is as follows.
I'm using ASP.NET 2.0 and VB.NET.
I have a login page. If I am an existing user, when I log in, my user details are popped in the respective textBoxes. Now I wish to change one of these fields. I edited one and then clicked on the Edit button to update the record. It's not updated but instead it brings the existing value from the text box.
How can I achieve this?
DBCmd.CommandText = "update IOMFNewMember set FirstName=#FirstName,MiddleName=#MiddleName,LastName=#LastNa,Gender=#Gender,DateofBirth=#DateofBirth,MartialStatus=#MartialStatus,DateofWedding=#DateofWedding,Nationality=#Nationality,ResidenceCountry=#ResidenceCountry,DateofJoiningIOMf=#DateofJoiningIOMf,EmailId=#EmailId,mobileno=#mobileno,AtPresent=#AtPresent,familykuwait=#familykuwait,DateofDeath =#DateofDeath where UserName=#Entery and MemberID=#MemberID"
For your requirement you have to run a sql command same as that u are using to populate the textboxes with the user details.
That is supposing you are using this in the login button click event
string strSql="select * from customers where id=" + txtLoginId.Text;
SqlConnection con=new SqlConnection(strCon);
con.Open();
SqlDataAdapter da=new SqlDataAdapter();
da.SelectCommand=new SqlCommand(strSql,con);
DataSet dset=new DataSet();
da.Fill(dset);
con.Close();
You will have to use this in the edit button click event :
string strSql="update EmployeeTable set password = '" + txtPassword.Text + "'";
SqlConnection con=new SqlConnection(strCon);
con.Open();
SqlCommand cmd=new SqlCommand(strsql, con);
cmd.ExecuteScalar();
con.Close();
Hope this will clear you confusion.
This is just an example. For a real time situation its advisable to use stored procedures only for any database query.