asp.net authentication and authorisation - c#

I am using Form authentication. Here I am using a login control and in (login.cs) control I am calling the following method to validate the user. Here I am using local name for both username and password and now I want to connect to the database so I can retrieve username and password.
private bool Authenticateme(string username, string password, bool remberusername)
{
String localusername = "username";
String localpassword = "amar";
if (username.Equals(localusername) && password.Equals(localpassword))
{
return true;
}
else
{
return false;
}
}

You could use the MemberShip and Role Providers

You need to implement OnAuthenticate by adding it like this:
<asp:Login OnAuthenticate="AuthenticateEventHandler" />
Add event handler in .cs file like this
private void OnAuthenticate(object sender, AuthenticateEventArgs e)
{
bool Authenticated = false;
Authenticated = SiteSpecificAuthenticationMethod(Login1.UserName, Login1.Password);
e.Authenticated = Authenticated;
}
implement SiteSpecificAuthenticationMethod that will validate user against database.
Here are the reference links:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.login.authenticate.aspx
http://forums.asp.net/t/1403132.aspx
Let me know if you need more help.

Try the following and create a SQL Server database with field username and password
SQlConnection con = new SqlConnection("Database connection string");
const string uName="UserName";
const string pWord="Password";
public bool getAuthenticate(string UserName,string Password)
{
con.Open();
SqlCommand cmd = new SqlCommand(con);
SQlParameter[] param=new SqlParameter[]{
new SqlParamter(uName,UserName),
new SqlParameter(pWord,Password)
};
cmd.Parameters.AddRanage(param);
SqlDataReader rd;
rd = cmd.executeReader();
if(rd.read())
{
con.Close();
return true;
}
else
{
con.Close();
return false;
}
}

Related

How to check if user is log in once enter a form using c# winform only, no asp.netc#

NO asp.net c# used
I need to know if user is login once he/she enter a form and if he/she is not login, he goes back to the login form. Everywhere I saw people use asp.net to achieve that but I want to know how to do it without using asp.net.
public DataTable Login(String Username, String Password)
{
server = "localhost";
database = "xxxx";
uid = "root";
password = "";
string MySQLConnectionString = $"datasource=127.0.0.1;port = 3306; SERVER={server}; DATABASE={database}; USERNAME={uid}; PASSWORD={password};sslmode=none";
MySqlConnection db_Conn = new MySqlConnection(MySQLConnectionString);
MySqlCommand cmd = new MySqlCommand();
db_Conn.ConnectionString = MySQLConnectionString;
string username_txtfield = username_txtbox.Text;
string pw_txtfield = password_txtbox.Text;
try
{
db_Conn.Open();
cmd.Connection = db_Conn;
cmd.CommandText = "SELECT count(*),user_id,person_username,role_id FROM user_tb " +
"WHERE person_username=#username " +
"AND user_password=#password";
cmd.Prepare();
cmd.Parameters.AddWithValue("#username", username_txtfield);
cmd.Parameters.AddWithValue("#password", pw_txtfield);
MySqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
db_Conn.Close();
return dt;
}
catch (Exception ex)
{
throw ex;
}
}
login btn in my login form
private void button1_Click(object sender, EventArgs e)
{
//login();
try
{
DataTable result = Login(username_txtbox.Text, password_txtbox.Text);
if (result.Rows.Count == 1)
{
this.Hide();
string role = result.Rows[0]["role_id"].ToString();
switch (role)
{
case "3":
MessageBox.Show("User login successfully!");
user_form_page();
break;
case "1":
MessageBox.Show("Admin login successfully!");
//this.Hide();
Admin_page admin_form = new Admin_page();
admin_form.ShowDialog();
this.Close();
break;
}
}
else
{
MessageBox.Show("INVALID USERNAME OR PASSWORD");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Of course the ASP.Net identity services is a mature way of doing such a task but if you want you can have your own method of authentication but, you will need to implement many things.
Many of the stuff you need is actually based on the scenario you are implementing but the most basic thing you need is a static user that will be used via your methods to see if the user is already logged in or not. For example you can have:
public static class Authentication
{
public static User CurrentUser { get; private set; }
public static bool Login(User user)
{
if(user == null)
throw new ArgumentException("Invalid user","user");
CurrentUser = user;
}
}
This is just the most basic implementation of such a thing you can then check if CurrentUser is null or not and direct user to login page or show her the results.
As your requirements grow you will need to implement more stuff. A logout, a local or remote database for users, store currently logged in user in disk so that she doesn't need to login again after closing the app and many other things
Edit
Based on your new information you can add this line to your login button click like this:
if (result.Rows.Count == 1)
{
Authentication.Login(new User(result.Rows[0]["username"],result.Rows[0]["role_id"])
//The rest of code
}
I have also presumed that you have a class like:
class User
{
public string Name { get; }
public int RoleId { get; }
public User(string name, int roleId)
{
Name = name;
RoleId = roleId;
}
}
And then you have to check Authentication.CurrentUser against null in your user form or admin form constructors to ensure user is login you can use the information in Authentication.CurrentUser to show logged in user name or role or any other info.
I hope this helps you. If you need more info please say so.

wpf - LDAP always returns false when validating

My login window uses LDAP to authenticate users. However, when validating, it always returns false.
Here is the code for validation which I got from CodeProject:
public bool fnValidateUser()
{
bool validation;
try
{
LdapConnection lcon = new LdapConnection
(new LdapDirectoryIdentifier((string)null, false, false));
NetworkCredential nc = new NetworkCredential(Environment.UserName,
txtPassword.SecurePassword, Environment.UserDomainName);
lcon.Credential = nc;
lcon.AuthType = AuthType.Negotiate;
// user has authenticated at this point,
// as the credentials were used to login to the dc.
lcon.Bind(nc);
validation = true;
}
catch (LdapException)
{
validation = false;
}
return validation;
}
txtPassword.SecurePassword is the PasswordBox. When I enter my password/pin and hit login, it displays the MessageBox for whenever validation is false.
What am I doing wrong?
UPDATE: The exception indicates "The LDAP Server is Unavailable", at this line lcon.Bind(nc);
You can try this sample piece of code.
// the username and password to authenticate
const string domain = "OU=Organization,DC=mydomain,DC=com";
string password = "mypass";
string userName = "myuser";
// define your connection
LdapConnection ldapConnection = new LdapConnection("ldap.mydomain.com:389");
try
{
// authenticate the username and password
using (ldapConnection)
{
// pass in the network creds, and the domain.
var networkCredential = new NetworkCredential(username, password, domain);
// if we're using unsecured port 389, set to false. If using port 636, set this to true.
ldapConnection.SessionOptions.SecureSocketLayer = false;
// since this is an internal application, just accept the certificate either way
ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
// to force NTLM\Kerberos use AuthType.Negotiate, for non-TLS and unsecured, just use AuthType.Basic
ldapConnection.AuthType = AuthType.Basic;
// authenticate the user
ldapConnection.Bind(networkCredential);
}
catch (LdapException ldapException)
{
//Authentication failed, exception will dictate why
}
}
I went ahead and found another approach for this, without using LDAP.
PrincipalContext adContext = new PrincipalContext(ContextType.Machine);
private async void btnLogin_Click(object sender, RoutedEventArgs e)
{
try
{
using (adContext)
{
if (adContext.ValidateCredentials(txtUsername.Text, txtPassword.Password))
{
MainWindow main = new MainWindow();
main.Show();
main.txtLoggedInUser.Text = UserPrincipal.Current.DisplayName;
this.Close();
}
else
{
MessageBox.Show("Incorrect Username or Password!");
}
}
}
catch(Exception ex)
{
var exceptionDialog = new MessageDialog
{
Message = { Text = ex.ToString() }
};
await DialogHost.Show(exceptionDialog, "RootDialog");
}
}

WPF: Get closed window result in app.xaml.cs

Seemed to have this working before, just making a login system for my application. Got it checking a local database for users and creating an object with the user information. But when the user logs in the login window should close and display the main window.
As this happens I need to access data from the login window which I have done like so:
protected override void OnStartup(System.Windows.StartupEventArgs e)
{
if (!AreSettingsSet())
{
Window LoginWindow = new Views.LoginWindow();
LoginWindow.ShowDialog();
//Waits until closed.
//If the login form was closed properly, handle the user
if (LoginWindow.DialogResult == true)
{
MessageBox.Show("Logged in correctly!");
//Add the user to the list of logged users
User returned = LoginWindow.returnUser;
MessageBox.Show("First name:" + returned.FirstName);
LoggedUsers.Add(returned);
}
else
{
//Unexpected window close, possible Alt + F4, shutdown!
MessageBox.Show(Messages.UnexpectedClose);
this.Shutdown();
}
// Recheck the settings now that the login screen has been closed.
if (!AreSettingsSet())
{
}
}
this.MainWindow = new Views.Main();
this.MainWindow.Show();
}
Here is the LoginWindow:
//Give App access to user object outside of this form
public User returnUser
{
get
{
return user;
}
}
//Public user object, start empty
User user = new User();
//Check the login
private void doLogin(string email, string password)
{
//Connect to database
using (SqlConnection myConnection = new SqlConnection(Settings.ConnectionString))
{
//Try and open the connection
try
{
myConnection.Open();
}
catch (Exception)
{
//Unable to connect to database, just return
MessageBox.Show(Messages.UnableOpenConnection);
return;
}
string salt = null;
bool found = false;
using (SqlCommand command = new SqlCommand(Queries.GetSalt, myConnection))
{
//Fetch the salt for the entered email address
command.Parameters.Add(new SqlParameter("#email", email));
SqlDataReader reader = command.ExecuteReader();
//Read the data
reader.Read();
if (reader.HasRows)
{
salt = reader["salt"].ToString();
found = true;
}
//Close the reader
reader.Close();
}
if (found == true)
{
if (salt.Length == 32)
{
using (SqlCommand command = new SqlCommand(Queries.GetSingleUser, myConnection))
{
//Salt the password
string saltedPassword = Encryption.sha256(password + salt);
//Add paramaters
command.Parameters.Add(new SqlParameter("#email", email));
command.Parameters.Add(new SqlParameter("#password", saltedPassword));
SqlDataReader reader = command.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
//Populate the login instance
user.ID = Convert.ToDecimal(reader["id"]);
user.FirstName = reader["firstname"].ToString();
user.LastName = reader["lastname"].ToString();
user.Email = reader["email"].ToString();
user.Permissions = Convert.ToInt16(reader["permissions"]);
//Close the reader
reader.Close();
//See if user has a thumbnail picture and save it's location
string thumbLoc = Directory.GetCurrentDirectory() +
"\\Users\\DisplayPictures\\" +
user.FirstName + user.LastName + ".png";
if (File.Exists(#thumbLoc))
{
user.ThumbLoc = thumbLoc;
}
else
{
user.ThumbLoc = Directory.GetCurrentDirectory() + "\\Users\\DisplayPictures\\user.png";
}
//Found user and created object, close this window safley
this.DialogResult = true;
this.Close();
}
else
{
//Unable to find a user
MessageBox.Show(Messages.NoUserFound);
return;
}
}
}
else
{
//Salt is the incorrect length
MessageBox.Show(Messages.InvalidSalt);
return;
}
}
else
{
MessageBox.Show(Messages.NoUserFound);
}
}
}
I'm getting an error here User returned = LoginWindow.returnUser; saying:
'System.Windows.Window' does not contain a definition for 'returnUser'
and no extension method 'returnUser' accepting a first argument of
type 'System.Windows.Window' could be found (are you missing a using
directive or an assembly reference?)
Please help me resolve this, and if i'm going about the login wrong please suggest changes!
That's because you declared the LoginWindow variable of type Window, instead of LoginWindow. LoginWindow has a returnUser property, but Window doesn't. Change the declaration to this:
Views.LoginWindow loginWindow = new Views.LoginWindow();
or just
var loginWindow = new Views.LoginWindow();
BTW, the convention in C# is to name local variables in camelCase, not PascalCase. For types and public members (methods, properties etc) you should use PascalCase. So the LoginWindow variable should be named loginWindow, and the returnUser property should be ReturnUser.

Update data using n-tier does nothing

I have got 3-tier where carry out my code in business layer I run code for update
public override bool LoadProperties2List(string TypeOfOperation)
{
SortedList Sl = new SortedList();
Sl.Add("#CommandType", TypeOfOperation);
Sl.Add("#UserName",UserName);
Sl.Add("#SecondarySchool",SecondarySchool);
Sl.Add("#University",University);
Sl.Add("#Qualification",Qualification);
Sl.Add("#JobTitle",JobTitle);
Sl.Add("#Company",Company);
Sl.Add("#PhotoUrl", PhotoUrl);
ProcedureName = "MangeUserInfo";
if (db.RunProcedure(ProcedureName, Sl) == 1)
return true;
else
return false;
}
public bool updateUser(string User, string SecondaryS, string Unvi, string Qua, string jobtitle, string company)
{
this.UserName = User;
this.SecondarySchool = SecondaryS;
this.University = Unvi;
this.Qualification = Qua;
this.JobTitle = jobtitle;
this.Company = company;
if (Update())
return true;
else
return false;
}
and in data access layer
public void ConnectDB(CommandType CT,string ProNameSQl)
{
cn = new SqlConnection("Data Source=.;Initial Catalog=Conversation;Integrated Security=True");
cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CT;
cmd.CommandText = ProNameSQl;
cn.Open();
}
public int RunProcedure(string ProcedureName, SortedList Paraval)
{
ConnectDB(CommandType.StoredProcedure, ProcedureName);
for (int x = 0; x < Paraval.Count; x++)
{
try
{
cmd.Parameters.AddWithValue(Paraval.GetKey(x).ToString(), Paraval.GetByIndex(x));
}
catch
{
;
}
}
return ExceNoneQuery();
}
and then in another layer I use this method to call procedure process kind and run
public bool Update()
{
return LoadProperties2List("u");
}
at last layer presentation layer
I do that
protected void btnsave_Click(object sender, EventArgs e)
{
//upadate info
bool Result = false;
UsersInfo Upd = new UsersInfo();
try
{
Result = Upd.updateUser(username, TxtSecondarySchool.Text, TxtUniversity.Text, TxtQualification.Text, TxtJobTitle.Text, TxtCompany.Text);
if (Result==true)
lblMessage.Text = "Record Updated Successfully.";
else
lblMessage.Text = "Record couldn't updated";
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
} finally
{
Upd = null;
}
}
When I run the code only the result is
lblMessage.Text = "Record couldn't updated";
What is the error which makes it not to work correctly?
I also find something strange that the textboxes doesn't take the new values it pass the same value despite change why? I need help
The error is that the textbox loads in a routine in the Page's Startup event, with the routine placed outside the If IsNotPostback loop. So, the default value just reloads every time the page is refreshed, and thus appears to be 'unchangeable'.

Login using WCF service application on a asp.net web application

I'm currently developing a dating site for a school project, and I'mm currently trying to make a log in feature for it. We are not supposed to use the automatic register and login feature.
Any contact we have with the database should go through the WCF service application. I know how to implement it without using the WCF, but I need to use it now, and I can't find this on Google after searching .
public bool login(string UserName, string PassWord, bool isActive = true) {
try {
DALDataContext db = new DALDataContext();
var qry = from m in db.tblUsers
where m.userName == UserName && m.password == PassWord && m.isActive == isActive
select m;
if (qry.Count() > 0) {
return true;
} else {
return false;
}
}
catch (Exception) {
return false;
}
}
That's how I made it, so this should work if I implement it in my web application
like this:
ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client();
protected void btnLoginUser_Click1(object sender, EventArgs e) {
try {
string UserName = txtUserName.Text;
string PassWord = txtPassWord.Text;
obj.login(UserName, PassWord);
if (true) {
Session["me"] = UserName;
Response.Redirect("~/MyProfile.aspx");
}
}
catch (Exception){
}
}
I've been working with this for hours, the register part of this works... so I'm doing something really wrong or something. I'm using Visual Studio 2010 and SQL Server 2008 R2.
[SOLVED]
this is how i solved it
protected void btnLoginUser_Click1(object sender, EventArgs e)
{
try
{
string UserName = txtUserName.Text;
string PassWord = txtPassWord.Text;
bool isActive = true;
if (obj.login(UserName, PassWord, isActive))
{
Session["me"] = UserName;
Response.Redirect("~/MyProfile.aspx");
}
else
{
lblErr.Text = "fail";
}
}
catch (Exception)
{
}
}
}
}
You are ignoring the return value of your login method:
obj.login(UserName, PassWord); // <-- returns true/false.
if (true) // <-- Why?
{
...
Did you mean to do
if (obj.login(UserName, PassWord))
{
Session["me"] = UserName;
Response.Redirect("~/MyProfile.aspx");
} ...
Suggest to return user from WCF service by name, like:
public tblUser login(string UserName);
In the client side you can retrieve user by name:
var user = obj.login(UserName);
if (user != null && user.password == txtPassWord.Text)
DoLogin();
else
ShowError();

Categories