I'm developing a web page and when you sign up and login you need to complete your information (name, last name, career, gender).
I've created a stored procedure:
ALTER PROCEDURE [dbo].[añadirinfocontacto]
#id int,#apellidoP nvarchar(50),#apellidoM nvarchar(50),#nombre nvarchar(50),#idEspecialidad int,#sexo nvarchar(10)
AS
BEGIN
if(#id=1)
begin
update Tbl_alumnos set nombre=#nombre,apellido_paterno=#apellidoP,apellido_materno=#apellidoM,id_especialidad=#idEspecialidad,sexo=#sexo where id_usuarios=#id
end
else
if(#id=2)
begin
update Tbl_Maestros set nombre=#nombre,apellido_paterno=#apellidoP,apellido_materno=#apellidoM,id_especialidad=#idEspecialidad,sexo=#sexo where id_usuarios=#id
end
else
begin
update Tbl_Administradores set nombre=#nombre,apellido_paterno=#apellidoP,apellido_materno=#apellidoM,id_especialidad=#idEspecialidad,sexo=#sexo where id_usuarios=#id
end
END
Code:
public static EntUsuario Actualizar(int idU,string nombre, string Apellidop,string ApellidoM,int IdEsp,string sexo)
{
EntUsuario obj = null;
SqlCommand cmd = null;
SqlDataReader dr = null;
try
{
Conexion cn = new Conexion( );
SqlConnection cnx = cn.conectar();
cmd = new SqlCommand("añadirinfocontacto", cnx);
cmd.Parameters.AddWithValue("#id", idU);
cmd.Parameters.AddWithValue("#nombre", nombre);
cmd.Parameters.AddWithValue("#apellidoP", Apellidop);
cmd.Parameters.AddWithValue("#apellidoM", ApellidoM);
cmd.Parameters.AddWithValue("#idEspecialidad", IdEsp);
cmd.Parameters.AddWithValue("#sexo", sexo);
cmd.CommandType = CommandType.StoredProcedure;
cnx.Open();
cmd.ExecuteNonQuery();
cnx.Close();
}
catch (Exception e)
{
obj = null;
}
finally
{
cmd.Connection.Close();
}
return obj;
}
And the Cick button event
protected void btnConfirmar_Click(object sender, EventArgs e)
{
Guid guid = (Guid)Membership.GetUser().ProviderUserKey;
EntUsuario obj = GbUsuario.Actualizar(Convert.ToInt32(guid),txtNombre.Text,txtApP.Text,txtApM.Text,Convert.ToInt32(dpEspecialidad.SelectedValue),RadioButtonList1.SelectedValue);
}
I want to get de user's ID but I don't know what to do, I've read about Session["user_id"], Membership.getUser, I also read that I need to configure web.config.
If I use the sample code above I use Membership.getUser but appears an error saying that it couldn't conect to database
enter code hereYou can get the current user with the following code:
var user = System.Web.HttpContext.Current.User
You can force users to log in by adding this to the web.config:
<configuration>
<system.web>
<authentication mode="Windows" />
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>
Related
I want any user to be restricted if they are not logged in.
suppose if they try to access any page by pasting the link still they are redirected to login page.
LoginPage
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Employee where UName =#username and UPassword=#password", con);
cmd.Parameters.AddWithValue("#username", UName.Text);
cmd.Parameters.AddWithValue("#password", UPassword.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Redirect("Details.aspx");
}
}
I think using <allow> section in web.config can help you:
<!--Deny access for 'images' folder-->
<location path="images">
<system.web>
<authorization>
<allow users="?"/> <!--A question mark (?) denies anonymous users-->
</authorization>
</system.web>
</location>
<!--Will deny anonymous users for all pages-->
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
More about it here: https://msdn.microsoft.com/en-us/library/acsd09b0(v=vs.85).aspx
You can achieve it through session in asp.net:
Create a session after the successful login of the user like as follows
Login Page:
Include the below namespace.
using System.Web.SessionState;
after user entered the user name and password:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Employee where UName =#username and UPassword=#password", con);
cmd.Parameters.AddWithValue("#username", UName.Text);
cmd.Parameters.AddWithValue("#password", UPassword.Text);
//Blah,Blah,Blah...
if(user=authenticated user) //your condition goes here
{
session["Sid"]=Session.SessionID;
//Blah,Blah,Blah...
}
Now in every page which you want to secure should have this follows:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Sid"] == null)
{
Response.Redirect("Login.aspx");
}
}
In web.config:
<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="120" />
I hope this helps...
i am doing a project in asp.net. it uses a login feature which i have implemented with 2 textboxes and a button. nothing fancy.
so now i have to distinguish which kind of user is logged in as there are different roles like admin, user, guest...
so what i need to know is what Session["UserAuthentication"] is and what it does...i think that i can add this data to an extra table to log all the sessions...is this a good approach?
here is my authentication method:
protected void Button1_Click(object sender, EventArgs e)
{
string username = tbUsername.Text;
string pwd = tbPassword.Text;
string s;
s = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(s);
con.Open();
string sqlUserName;
sqlUserName = "SELECT Username, UserPassword FROM Benutzer WHERE Username ='" + username + "' AND UserPassword ='" + pwd + "'";
SqlCommand cmd = new SqlCommand(sqlUserName, con);
string CurrentName;
CurrentName = (string)cmd.ExecuteScalar();
if (CurrentName != null)
{
Session["UserAuthentication"] = username;
Session.Timeout = 1;
Response.Redirect("Default.aspx");
}
else
{
lblStatus.ForeColor = System.Drawing.Color.Red;
lblStatus.Text = "Benuztername/Password ungültig!";
}
}
Session["UserAuthentication"] is a variable that will hold the value of username globally across all pages for that particular current user.
Yes, you can add the data in a SQL Table. For that you need to add this in your web.config file.
<sessionState mode="SQLServer" sqlConnectionString="data source=yourDataSource;user id=username;password=password" cookieless="false" timeout="20" />
Just in case if your are wondering where in Database does the SessionId of the variable is stored - for that you need to install the ASPState Database on your Server. And pass the connection string accordingly on the web.config file as described above.
How to add the Database ASPState??
1. Go to this path: C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319
2. Here you will find a script named InstallSqlState.sql which you need to execute in your SQL server.
any help would be great thank you. not sure why its all ways returning a null
I'm not sure if its even connecting to the database.
my web config file
<configuration>
<connectionStrings>
<add name="accessConnectionString" providerName="Microsoft.Jet.OLEDB.4.0" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\***\Desktop\pratice\AccessTest\App_Data\TheList.mdb;Persist Security Info=True"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
</configuration>
middle tier code to check if user is in the database if they are return something if not return null
OleDbConnection sconn = new OleDbConnection();
OleDbCommand scmd = new OleDbCommand();
public DBMiddleTier()
{
try
{
// set up the connection strings
sconn.ConnectionString = ConfigurationManager.ConnectionStrings["accessConnectionString"].ToString();
}
catch(Exception ex)
{
throw ex;
}
}//end of constructor
//class to check membership
public object checkMembership(string logid, string password)
{
try
{
sconn.Open();
//set propertiers of the command
scmd.Connection = sconn;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "select * from SubDealers where LoginID = #InputUsername and Password = #InputPassword";
scmd.Parameters.Clear();
OleDbParameter checkUsername = scmd.Parameters.Add("#InputUsername", OleDbType.VarChar, 50);
checkUsername.Value = logid;
OleDbParameter checkPassword = scmd.Parameters.Add("#InputPassword", OleDbType.VarChar, 50);
checkPassword.Value = password;
object result = scmd.ExecuteScalar();
return result;
}
catch (OleDbException sqx)
{
throw sqx;
}
finally
{
sconn.Close();
}
}//end of method
my code behind page
try
{
object result = dm.checkMembership(txtLoginID.Text, txtPassword.Text);
if (result != null)
{
Response.Redirect("https://www.google.com/");
}
else
{
txtLoginID.Text = "";
txtPassword.Text = "";
Page.ClientScript.RegisterStartupScript(this.GetType(), "notAmember", "alert('Sorry wrong id or password');", true);
}
}
catch (Exception ex)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
}
have you tried this?
select * from [SubDealers] where [LoginID] = #InputUsername and [Password] = #InputPassword"
I'm using ASP.NET forms authentication in my web application.recently i found a strange behavior. everything was working fine in production environment.with .net 4.0 and IIS 7.in the login user enter username and password and logged in then suddenly HttpContext.Current.User.Identity.Name is lost.this does not happen every time only in some occasions.i have unable to reproduce the issue in my development environment.i have checked if(HttpContext.Current.User.Identity.IsAuthenticated) it's also true authentication ticket user data is not empty also.only HttpContext.Current.User.Identity.Name is empty.plz help
code in Login button
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
dtUserDetails = new DataTable();
if (UserRepositoryBL.ValidateUser(txtUserName.Text.Trim(), Password.Text.Trim(), out dtUserDetails))
{
AuthUser au = new AuthUser();
if (dtUserDetails.Rows.Count > 0)
{
DataRow DR = dtUserDetails.Rows[0];
au.UserID = Convert.ToInt32(DR["UserID"].ToString());
au.UserNo = DR["UserNo"].ToString();
au.UserName = DR["UserName"].ToString();
au.Password = DR["Password"].ToString();
}
string userData = au.ToString();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
2, // Version number
txtUserName.Text.Trim(), // Username
DateTime.Now, // Issue date
DateTime.Now.AddMinutes(60), // Expiration date
false, // Persistent?
userData // User data
);
string eticket = FormsAuthentication.Encrypt(ticket);
if (Request.Cookies[txtUserName.Text] != null)
{
//HttpCookie myCookie = new HttpCookie(txtUserName.Text);
//myCookie.Expires = DateTime.Now.AddDays(-1d);
Request.Cookies[txtUserName.Text].Expires = DateTime.Now.AddDays(-1d);
Request.Cookies.Remove(txtUserName.Text);
}
HttpCookie cookie = new HttpCookie("SiteCookie", eticket);
// HttpCookie cookie = new HttpCookie("SiteCookie", eticket);
cookie.Expires = DateTime.Now.AddMinutes(60);
FormsAuthentication.SetAuthCookie(txtUserName.Text, false);
// cookie.Path = FormsAuthentication.FormsCookiePath;
FormsAuthentication.RenewTicketIfOld(ticket);
Response.Cookies.Add(cookie);
BasePage.ActivityLog("User Login", txtUserName.Text.Trim(), true, Request.RawUrl);
string url = FormsAuthentication.GetRedirectUrl(txtUserName.Text, false);
Response.Redirect(url);
// FormsAuthentication.RedirectFromLoginPage(LoginUser.UserName, false);
}
else
{
FailureText.Text = "Your login attempt was not successful. Please try again.";
}
}
catch (Exception ex)
{
throw ex;
}
}
web.config
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="60" cookieless="UseCookies" defaultUrl="~/Landing.aspx" protection="All"/>
</authentication>
<authorization>
<deny users="?" />
</authorization>
Your session time is limited to 60 minutes. Does the problem only occur for people with an expired session? Might explain why you can't reproduce this on your development machine because you simply don't wait that long?
I seem to cant set up an authentication system in asp.net
I have code for a login system:
protected void btnlogin_Click(object sender, EventArgs e)
{
PageUser myUser = new PageUser();
if (myUser.AuthenticateUser(txtUsername.Text, txtPassword.Text))
{
// entry found
HttpCookie myCookie;
DateTime now = DateTime.Now;
myCookie = new HttpCookie("UserName");
myCookie.Value = myUser.UserName;
myCookie.Expires = now.AddMinutes(30);
Response.Cookies.Add(myCookie);
myCookie = new HttpCookie("LoginID");
myCookie.Value = myUser.UserLoginID.ToString();
myCookie.Expires = now.AddMinutes(30);
Response.Cookies.Add(myCookie);
lblResult.Visible = false;
FormsAuthentication.SetAuthCookie(myUser.UserName + " " + myUser.UserLoginID.ToString(), true);
Response.Redirect("AdminView.aspx");
}
else
{
// entry not found
lblResult.Text = "<b>Invalid logon attempt<b>";
lblResult.ForeColor = System.Drawing.Color.FromName("Red");
lblResult.Visible = true;
}
}
The authentication method works fine, but when I do not login it still lets me redirect twords the AdminView even though the person didnt login.
Code I am having difficulty with:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
string userName = "";
string[] splits;
try
{
if (this.Page.User.Identity.IsAuthenticated)
{
splits = this.Page.User.Identity.Name.Split(new char[1] { ' ' });
userName = splits[0] + " " + splits[1];
}
else
{
Response.Redirect("default.aspx");
}
txtLoggedInUser.Text += " - " + userName;
}
catch
{
Response.Redirect("default.aspx");
}
}
I am not sure how to write this code so it would redirect a person back to the login page when they try to visit the admin page.
To restrict an unauthenticated user to the AdminView.aspx page, you have to add below into the configuration section of the web.configfile.
<location path="AdminView.aspx">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
<deny users="?"/> mean's the unauthenticated user will not be able to access the file/folder AdminView.aspx