i did my coding in console and used a system.console. write line in almost every if/else statement so as to display an error message if wrong values are entered of to say if what goes wrong. how ever am trying to apply the same analogy in web forms such that should there be a user error while running the conditions, an error message may be displayed to the user on the screen.
How do i go about displaying the errors?i know of item validations but cant apply that using if and else. however if i use try catch, i dont know which code displays the error message to user. but i know for sure i cant use SC.writelines.
a sample of my code is below.please advice..
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string strConn;
string userType;
strConn = "Provider=MIcrosoft.Jet.OLEDB.4.0;data Source=" +
Server.MapPath("App_Data/test.mdb");
OleDbConnection mDB = new OleDbConnection(strConn);
mDB.Open();
userClass aUser = new userClass();
if (aUser.verifyUser(mDB, Login1.UserName, Login1.Password))
{
userType = aUser.getUserDesc();
if (userType.ToLower() == "customer")
{
Response.Redirect("StaffMenu.aspx");
}
else if (userType.ToLower() == "front desk")
{
Response.Redirect("StaffMenu.aspx");
}
else if (userType.ToLower() == "technician")
{
Response.Redirect("StaffMenu.aspx");
}
else if (userType.ToLower() == "admin")
{
Response.Redirect("StaffMenu.aspx");
}
}
else
{
e.Authenticated = false;
}
mDB.Close();
when the program moves to the User class to run the verify method, it does so by running the following bock of code..
public bool verifyUser(OleDbConnection mDB, string userIDStr, string userPwrdStr)
{
string sqlQuery;
OleDbCommand cmd;
OleDbDataReader rdr;
//SC.Write("\n*******User Login********\nEnter User ID:");
//userIDStr = userIDInt.ToString();
//SC.Write("\nEnter User Password:");
//userPwrdStr = userPwrdStr;
sqlQuery = "SELECT UserID, UserPassword, UserDescription FROM UserTable WHERE UserID = " +
toSql(userIDStr);
cmd = new OleDbCommand(sqlQuery,mDB);
//Boolean valid = false;
//Boolean HasRows = false;
try
{
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
if (userIDStr == (string)rdr["UserID"])
{
if (userPwrdStr == (string)rdr["UserPassword"])
{
userDescStr = (string)rdr["UserDescription"];
if (userDescStr.ToLower() == "admin")
{
//SC.WriteLine("Welcome to Admin Main Menu");
return true;
}
else if (userDescStr.ToLower() == "front desk")
{
//SC.WriteLine("Welcome to Front Desk Staff Main Menu");
return true;
}
else if (userDescStr.ToLower() == "technician")
{
//SC.WriteLine("Welcome to Technical Staff Main menu");
return true;
}
else if (userDescStr.ToLower() == "customer")
{
//SC.WriteLine("Sorry, Customers are not allowed access to the Administrative page");
return true;
}
}
else
{
//SC.WriteLine("\nInvalid User Password, Please try again");
//verifyUser(mDB);
}
}
else
{
//SC.WriteLine("Invalid User ID, Please try again");
//verifyUser(mDB);
}
//HasRows = true;
}
rdr.Close();
}
catch (Exception ex)
{
SC.WriteLine(ex.Message);
}
return false;
}//=================================end verify User()
how ever if the wrong username or password is entered, how can i display an error message to the user as to which of the controls is receiving the wrong value...
am hoping to use this code to replace my SC.writelines that displays messages to the user....
You would probably build up a list of errors in a string and assign them to a label on the form, or potentially a ul tag.
I'd also recommend not differentiating whether or not a username or the password is invalid. If they don't manage to login, you should just display a 'Could not log in' message. If they get a correct username and an incorrect password, then using your method, I would know that I had guessed a correct username and could hammer away at passwords for that.
In addition, have you looked at the built in ASP.net login controls and the membership providers? They take care of a lot of this for you, or you can roll your own that integrates with the supplied controls.
Related
I have a controller form application and the security team they said there is a vulnerability you can put any user_id fom postman inside the controller like this
ForgotPassword/user_id
how I can remove this vulnerability check the code below:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult ForgotPassword(string emailId)
{
var helper = new Helper.Helper();
List<SqlParameter> args = new List<SqlParameter>();
args.Add(new SqlParameter("#Pin_email_id", emailId));
var req_resp = new Dictionary<string, object>();
try
{
using (DataSet dataset = helper.ExecuteSqlQuery("Web_Forgot_Password", args))
{
if (dataset != null && dataset.Tables.Count > 0 && dataset.Tables[0].Rows.Count > 0)
{
if (dataset.Tables[0].Rows[0]["Status"].ToString() == "Success")
{
req_resp["status"] = true;
req_resp["message"] = dataset.Tables[0].Rows[0]["Description"].ToString();
req_resp["code"] = dataset.Tables[0].Rows[0]["Code"].ToString();
string password = dataset.Tables[0].Rows[0]["user_password"].ToString();
SendForgotMail(emailId, dataset.Tables[0].Rows[0]["user_name"].ToString(), helper.Decrypt(password), dataset.Tables[0].Rows[0]["employee"].ToString());
return Json(req_resp);
}
else
{
req_resp["status"] = false;
req_resp["message"] = dataset.Tables[0].Rows[0]["Description"].ToString();
req_resp["code"] = dataset.Tables[0].Rows[0]["Code"].ToString();
return Json(req_resp);
}
}
else
{
req_resp["status"] = false;
req_resp["message"] = "Request Failed";
req_resp["code"] = "1005";
return Json(req_resp);
}
}
}
catch
{
var response = new
{
status = false,
message = "Request failed",
code = "1005"
};
return Json(response);
}
}
Well normally you store only password hashes in your database, which are not decryptable. Watching helper.Decrypt(password) in your code and sending the original password as a plain text in email is something painful. Normally I would just send a password reset link which can be used only once.
I checked the SqlParemater docs, it is added as a String value the way you use it, so it is not SQL injectable. Without the exact SQL I cannot tell much. I think they meant that it is SQL injectable, but then they should send evidence at least.
I'm working on a social network with ASP.NET and signalr. I have a simple login page, if it finds the user in the database it creates an Application variable and redirect the user to the profile page and in this page i invoke my Connect method declared in my hub class, this method takes the userid in the session and it give the friend list of this user. That works great when two or many users logged in at different time. The thing is, when two or several users logged in at the same time, the connect method declared in my hub takes the last user id stored in the Application variable and it give the friend list of this last user id and it send it to all user connected.
I can't find the correct approach.
Loggin Page code:
protected void btn_login_Click(object sender, EventArgs e)
{
Tbl_User user = new Tbl_User();
user = FonctionCommun.Login(txt_UserName.Text , txt_PassWord.Text);
if (user != null)
{
Application["UserID"] = user.UserID.ToString();
Response.Redirect("Profile.aspx");
}
else {
Label1.Visible = true;
}
}
My connect method code:
public void connect()
{
UserID = Guid.Parse(HttpContext.Current.Application["UserID"].ToString());
string OutPut = "";
if (ListOnlineUser.Count(x => x.UserID == UserID) == 0)
{
ListOnlineUser.Add(new OnlineUsers { UserID = UserID, ConnetionID = Guid.Parse(Context.ConnectionId) });
objchat.SetOnline(UserID);
ListFriends = objchat.GetFriendLoginStatus(UserID);
}
foreach (Tbl_User item in ListFriends)
{
if (item.Status == "1")
{
OnlineUsers onlineFriend = ListOnlineUser.FirstOrDefault(x => x.UserID == Guid.Parse(item.UserID.ToString()));
if (onlineFriend != null)
{
using (FIESTA_ADVISOREntities BD = new FIESTA_ADVISOREntities())
{
Tbl_User Obj_User = BD.Tbl_User.Where(o => o.UserID == UserID).FirstOrDefault();
if (Obj_User.ProfileImage != null)
{
string ext = BD.Assets.Where(o => o.url == Obj_User.ProfileImage).Select(o => o.MimeType).FirstOrDefault();
UserDetaille res = new UserDetaille() { UserID = Guid.Parse(Obj_User.UserID.ToString()), Username = Obj_User.UserName, ProfileImage = Obj_User.ProfileImage.ToString(), Ext = ext };
OutPut = JsonConvert.SerializeObject(res);
}
else {
UserDetaille res = new UserDetaille() { UserID = Guid.Parse(Obj_User.UserID.ToString()), Username = Obj_User.UserName, ProfileImage = "111", Ext = "png" };
OutPut = JsonConvert.SerializeObject(res); }
Clients.Client(onlineFriend.ConnetionID.ToString()).OnNewUserConnect(OutPut);
}
}
}
}
Clients.Caller.ShowFriends(ListFriends);
}
Try session variable instead of application variable. Application variable shared through out application working. So Whenever new user this is override. But if you use session variable that will never override by any other user
Also you can use query string in signalr in which you can pass userid as query string so in each request userid will be in query string
$.connection.hub.qs = 'userid=' + "UserId";
I have facebook integration done for my android app, now I have the FB login button also user can register for our application and login using his email id.
so I have 2 different ways to login.
Problem is that I m unable to get the values in the EditText field provided by user to login.
I m able to get the value in registeration page but not in the login page.
But if I remove all the codes used for FB integration it works fine..
I have a fragment activity.
Please help and let me know if any info needed..
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
try {
Log.i("TAG", "Inside Hash Key");
PackageInfo info = getPackageManager().getPackageInfo("com.package", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash :", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, mainFragment).commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
}
try {
Log.i("TAG", "Inside Hash Key");
PackageInfo info = getPackageManager().getPackageInfo("com.package", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash :", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
This is what I have in my oncreate.
public bool IsUserGroupMember(string user, string unit)
{
bool member = false;
try
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
string[] groups = unit.Split(',');
foreach (string word in groups)
{
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, word);
if (grp != null)
{
foreach (Principal p in grp.GetMembers(true))
{
if (p.SamAccountName == user)
{
member = true;
grp.Dispose();
ctx.Dispose();
return member;
}
}
}
else
{
grp.Dispose();
ctx.Dispose();
return member;
}
}
}
catch (COMException)
{
return member;
}
return member;
}
I'm using the method above to find if a user is member of a group in Active Directory, recursively. It works well..although sometimes I get a weird exception.
Specified method is not supported.
foreach (Principal p in grp.GetMembers(true)) is red (sorry I can't upload a picture of the exception). The weirdest thing is that it seems to be thrown randomly, and if I refresh the page it works well..
I tried to find a solution on the Internet but no happy news for now..
You should do this the other way around: get the user and then the authorization groups that this user is a member of - this call (.GetAuthorizationGroups on the UserPrincipal) already is searching the groups recursively for you!
public bool IsUserGroupMember(string user, string unit)
{
bool isMember = false;
try
{
// put the PrincipalContext in a using(..) block - then it's
// automatically, safely and properly disposed of at the end
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// get the user
UserPrincipal up = UserPrincipal.FindByIdentity(ctx, user);
if(up != null)
{
// get the authorization groups for the user
// this call is *RECURSIVELY* enumerating all groups
// that this user is a member of
var authGroups = up.GetAuthorizationGroups();
// now that you have the groups - just determine if the user
// is a member of the group you're looking for......
}
}
}
catch (COMException comEx)
{
isMember = false;
}
return isMember;
}
I finally ended up with a solution!
I just had to add my domain name, as follow:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "MyDomain");
It solved the problem right away!
And about the slowness..I used cookies, following this link.
for a mistake. I used a wrong command. I wanted to remove an user' role from the table aspnet_UsersInRoles.
I guess that the command might be
Roles.RemoveUserFromRole(userName, origin_role);
However I used a wrong command mistakenly.
Roles.DeleteRole(origin_role,false);
Originally the table has 4 roles. Now the RoleId in the table only has two,
61572264-4935-461d-9d8c-71f147f28c34
c09f25e6-fd6a-447b-8e0d-eba0cfc94e40
How can I find and recovery them?
Many many thanks.
Hate to say it, but you're hosed. The default ASP.Net providers don't include any sort of auditing or soft-delete. If you have a database backup, you can explore/restore from that.
Below you find the source code for the function you called.
It calls the dbo.aspnet_Roles_DeleteRole stored procedure.
I don't have access to an asp.net membership database at the moment, otherwise I would check for you.
You might want to check what the stored procedure does, but as ssyladin mentioned I doubt you will be able to recover anything (since you sent the throwOnPopulatedRole argument to false).
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
SecUtility.CheckParameter(ref roleName, true, true, true, 256, "roleName");
try {
SqlConnectionHolder holder = null;
try {
holder = SqlConnectionHelper.GetConnection(_sqlConnectionString, true);
CheckSchemaVersion( holder.Connection );
SqlCommand cmd = new SqlCommand("dbo.aspnet_Roles_DeleteRole", holder.Connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = CommandTimeout;
SqlParameter p = new SqlParameter("#ReturnValue", SqlDbType.Int);
p.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(p);
cmd.Parameters.Add(CreateInputParam("#ApplicationName", SqlDbType.NVarChar, ApplicationName));
cmd.Parameters.Add(CreateInputParam("#RoleName", SqlDbType.NVarChar, roleName));
cmd.Parameters.Add(CreateInputParam("#DeleteOnlyIfRoleIsEmpty", SqlDbType.Bit, throwOnPopulatedRole ? 1 : 0));
cmd.ExecuteNonQuery();
int returnValue = GetReturnValue(cmd);
if( returnValue == 2 )
{
throw new ProviderException(SR.GetString(SR.Role_is_not_empty));
}
return ( returnValue == 0 );
}
finally
{
if( holder != null )
{
holder.Close();
holder = null;
}
}
}
catch
{
throw;
}
}