How to validate password when TextMode="Password" - c#

I'm building a web application using the default master template in VS2010 - very new to doing this. I'm also using the Login.aspx page, but instead of using the built in user validation, my user info is in a database table. So Following instructions I found, I'm doing something wery similar to this:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
Boolean bauthenticated = false;
bauthenticated = isValidUser(Login1.UserName, Login1.Password);
if (bauthenticated)
{
e.Authenticated = true;
}
else
{
e.Authenticated = false;
}
}
The problem is that I put the method isValidUser in a .dll so it could be used elsewhere, and it is not receiving the password because the default behaivor is to blank it out. I even tried to set a string variable to Login1.Password, and pass the variable without success. I understand why this is happening, but can't find any info as to how to do this correctly. Do I need to put the user name and password into an object and pass that to my class constructor? I really don't want to connect to my database from every Login.aspx page I create to avoid sending the password over http.

Try to use the following code.
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
dtUserDetails = new DataTable();
if (UserRepositoryBL.ValidateUser(LoginUser.UserName.Trim(), LoginUser.Password.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(
1, // Version number
LoginUser.UserName.Trim(), // Username
DateTime.Now, // Issue date
DateTime.Now.AddMinutes(60), // Expiration date
false, // Persistent?
userData // User data
);
string eticket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie
(FormsAuthentication.FormsCookieName, eticket);
Response.Cookies.Add(cookie);
BasePage.ActivityLog("User Login", LoginUser.UserName.Trim(), true, Request.RawUrl);
string url = FormsAuthentication.GetRedirectUrl(LoginUser.UserName, false);
Response.Redirect(url);
// FormsAuthentication.RedirectFromLoginPage(LoginUser.UserName, false);
}
else
{
LoginUser.FailureText = "Your login attempt was not successful. Please try again.";
}
}
catch (Exception ex)
{
throw ex;
}
}
dtUserDetails is a out parameter which contains the user details like password,username,etc.. on successful login.datatable returns empty if invalid login.with in userData string all those information will be available.then u can retrieve those from any page using User Authenticated Ticket

Related

session get cleared after login

I am having an issue with sessions getting cleared during the login process. When I debugged it, I find that the login process works correctly, the authentication passes, and the session value gets stored (Session["user_register_id"]).
Then I store some values in the session for "user_register_id" and it stores successfully.
The app redirects to a page that checks if the user is authenticated (which is true) and checks a session Session["user_register_id"] (which for some reason is null).
public void LogInUser(string email, string password, bool rememberMe)
{
// Validate the user password
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
var result = signinManager.PasswordSignIn(email, password, rememberMe, shouldLockout: false);
if (result == SignInStatus.Success)
{
var user = manager.Find(email, password);
var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
Request.GetOwinContext().Authentication.SignIn(new AuthenticationProperties() { }, userIdentity);
bool flg = SetSessionFields();
if (flg)
{
Session["user_register_id"] = GetUserId();
Users.InsertUserLoginInfo(userIdentity.GetUserId(), "Login Success");
var redirUrl = HttpUtility.UrlDecode(Request["ReturnUrl"]);
if (!string.IsNullOrWhiteSpace(redirUrl))
{
var mappedPath = Page.MapPath(redirUrl.Trim()) + ".aspx";
if (File.Exists(mappedPath))
IdentityHelper.RedirectToReturnUrl(redirUrl.Trim(), Response);
}
else
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else
{
InvalidLogin();
Users.InsertUserLoginInfo(userIdentity.GetUserId(), "Login Failed, invalid department");
}
}
else
InvalidLogin();
}
On page I am checking the user and the session value
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user_register_id"] == null || !User.Identity.IsAuthenticated)
Response.Redirect("./App/Account/Login.aspx");
}
In the page, the user is authenticated but the session value is empty.
Any idea why?
Update
I have scheduler that is used to run some function at the start of the application.
public void SchedulerStart()
{
TimerCallback callbackDaily = new TimerCallback(LicenceValidation.RunValidation);
Timer dailyTimer = new Timer(callbackDaily, null, TimeSpan.Zero, TimeSpan.FromHours(2));
}
in the Global.asax I added to the application start this code:
App.Scheduler.JobScheduler myScheduler = new App.Scheduler.JobScheduler();
myScheduler.SchedulerStart();
Inside the scheduled function there is writing to file
System.IO.File.WriteAllBytes(filePath, encContent);
which when I deleted the line everything work just fine.
Any help?
Note: the scheduler code form code

FormsAuthentication cookie not setting UserData values

I've accidentally jumped into the world of cookies and am trying to understand what's going on. I have a web app developed in Visual Studio 20120/C# using FormsAuthentication. When I first developed the app, I created a few fields to store in the authentication cookie: personID, firstName, and admin, the string looks like this: 777|Jimmy|1. Everything has worked well since then. Now I've added a fourth field to the end of the blur called "secBlur". When I do this and try to retrieve the value of secBlur, it tells me the array range is out of bounds because the earlier version of the cookie did not contain this field...makes sense. I've spent the past couple of days trying to rewrite the validity check for my cookie, and I thought I had everything figured out. However, when I go to write the new userData string into the cookie, it doesn't appear to be doing it. My code is below, I'll try to walk through what I'm doing...
In the page_load of my master page, the first thing I'm doing is making a call to a cookie class I created to check that the cookie is the correct version:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
authCookie ac = new authCookie();
ac.validate();
LoginName ct = (LoginName)loginStatus.FindControl("HeadLoginName");
if (ct != null)
{
formValues fv = new formValues();
ct.FormatString = fv.firstName;
}
}
}
My entire cookie class is below. In the Validate method I'm checking for the existence of the cookie and then checking to see that it is the correct version and that userData exists. If it's not the correct version or userData does not exist I call the getUserData method to retrieve the most current info for this year, create a new ticket, store the ticket into the cookie, and then save the cookie. I think the line saving the cookie is the problem, but I'm not sure.
using System;
using System.Data.SqlClient;
using System.Runtime.Remoting.Contexts;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;
namespace DMC.Classes
{
public class authCookie
{
public void cookiePrep(Login LoginUser)
{
string userData = "unknown|unknown";
// Concat the values into a single string to pass into the cookie
userData = getUserData(LoginUser.UserName);
// Create the cookie that contains the forms authentication ticket
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(LoginUser.UserName, LoginUser.RememberMeSet);
// Get the FormsAuthenticationTicket out of the encrypted cookie
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(3,
ticket.Name,
ticket.IssueDate,
ticket.Expiration,
LoginUser.RememberMeSet,
userData,
ticket.CookiePath);
// Manually add the authCookie to the Cookies collection
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
HttpContext.Current.Response.Cookies.Add(authCookie);
string redirUrl = FormsAuthentication.GetRedirectUrl(LoginUser.UserName, LoginUser.RememberMeSet);
if (redirUrl == null)
redirUrl = "../default.aspx";
HttpContext.Current.Response.Redirect(redirUrl);
}
public string getUserData(string userID)
{
string userData = "";
// Grab this user's firstname, personID, and Admin status
string mySQL = "exec get_adBasicInfo #userName";
string cf = System.Configuration.ConfigurationManager.ConnectionStrings["DistrictAssessmentDWConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(cf);
SqlCommand command = new SqlCommand(mySQL, connection);
command.Parameters.AddWithValue("#userName", userID);
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
userData = string.Concat(dr["personID"], "|", dr["firstName"], "|", dr["secBlur"]);
}
dr.Close();
return userData;
}
public void validate()
{
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
/**********************************************************************************************************************
* Version 3: Added the secBlur field onto the userData string to see if logged in user needs to have sensitive *
* data blurred out (0: Normal; 1: Blur Sensitive Data *
**********************************************************************************************************************/
if ((ticket.Version != 3) || (ticket.UserData == ""))
{
string userData = getUserData(ticket.Name);
FormsAuthenticationTicket newAuthTicket = new FormsAuthenticationTicket(3,
ticket.Name,
ticket.IssueDate,
ticket.Expiration,
ticket.IsPersistent,
userData,
ticket.CookiePath);
authCookie.Value = FormsAuthentication.Encrypt(newAuthTicket);
HttpContext.Current.Response.SetCookie(authCookie);
}
}
}
}
}
At this point control passes back out to the load_page function of my master page and attempts to retrieve the firstName of the user from the cookie by calling my formValues class, below:
using DMC.Classes;
using System.Web;
using System.Web.Security;
namespace DMC.Classes
{
public class formValues : System.Web.Services.WebService
{
public string firstName = getFirstName();
public string personID = getPersonID();
public string secBlur = getSecBlur();
private static string getUserDataString(int ix)
{
string retValue = "";
if (HttpContext.Current.Request.IsAuthenticated)
{
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
if (ticket != null)
{
string[] userData = { "" };
char[] delimiterChar = { '|' };
userData = ticket.UserData.Split(delimiterChar);
retValue = userData[ix];
}
}
}
return retValue;
}
private static string getFirstName()
{
string firstName = getUserDataString(1);
return firstName;
}
private static string getPersonID()
{
string personID = getUserDataString(0);
return personID;
}
private static string getSecBlur()
{
string secBlur = getUserDataString(2);
return secBlur;
}
}
}
On attempting to getFirstName, I'm getting an error in the getUserDataString method when attempting to set the retValue because the userData array is empty. So can somebody please tell me where I'm going wrong?
In my authCookie class, I changed from:
HttpContext.Current.Response.SetCookie(authCookie);
to
HttpContext.Current.Response.Add(authCookie);
I'm not a fan of this though, because from what I read, if the cookie already exists, this does not overwrite the cookie, it will just create a duplicate. But I've been playing around and it's the only thing that seems to work. If somebody has a better solution, please share!!

Cannot retrieve cookie

Using FormsAuthentication, I am creating a FormsAuthenticationTicket, encrypting, adding this to a cookie using Response.Cookies.Add(authCookie). I then do a redirect using Response.Redirect to the original page that was requested. There is code in the Global.asax in the Application_AuthenticateRequest method that looks to retrieve the cookie - HttpCookie authCookie = Context.Request.Cookies[cookieName]. For some reason, however, when it hits the Global.asax code after the redirect is called, there are no cookies in the collection. At this point, I am a bit stumped as to why it is losing the cookie from the collection. Any thoughts as to why this would happen? Right now, I am just working within localhost.
Login Page Code:
string adPath = "LDAP://ldapserveraddress";
LdapAuthentication adAuth = new LdapAuthentication(adPath);
try
{
if (true == adAuth.IsAuthenticated("ES", txtUsername.Text, txtPassword.Text))
{
string groups = adAuth.GetGroups();
//Create the ticket, and add the groups.
bool isCookiePersistent = chkPersist.Checked;
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
txtUsername.Text, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups);
//Encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
//Create a cookie, and then add the encrypted ticket to the cookie as data.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
if (true == isCookiePersistent)
authCookie.Expires = authTicket.Expiration;
//Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);
string redirect = FormsAuthentication.GetRedirectUrl(txtUsername.Text, false);
//You can redirect now.
Response.Redirect(redirect,false);
}
else
{
errorLabel.Text = "Authentication did not succeed. Check user name and password.";
}
}
catch (Exception ex)
{
errorLabel.Text = "Error authenticating. " + ex.Message;
}
}
Global.asax Code (Application_AuthenticateRequest):
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if (null == authCookie)
{
//There is no authentication cookie.
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch (Exception ex)
{
//Write the exception to the Event Log.
return;
}
if (null == authTicket)
{
//Cookie failed to decrypt.
return;
}
//When the ticket was created, the UserData property was assigned a
//pipe-delimited string of group names.
string[] groups = authTicket.UserData.Split(new char[] { '|' });
//Create an Identity.
GenericIdentity id = new GenericIdentity(authTicket.Name, "LdapAuthentication");
//This principal flows throughout the request.
GenericPrincipal principal = new GenericPrincipal(id, groups);
Context.User = principal;
}`
I was able to resolve my issue by adjusting the data that was being stored in the userData of the FormsAuthenticationTicket. It appears as though the amount of data that I was trying to insert exceeded a maximum. Once I removed, everything works as expected.

Can't Connect to SalesForce in C#

I am following this tutorial http://wiki.developerforce.com/page/Integrating_Force.com_with_Microsoft_.NET
However, I am getting this error:
LOGIN_MUST_USE_SECURITY_TOKEN: Invalid username, password, security
token; or user locked out. Are you at a new location? When accessing
Salesforce--either via a desktop client or the API--from outside of
your company’s trusted networks, you must add a security token to your
password to log in. To receive a new security token, log in to
salesforce.com at http://login.salesforce.com and click Setup | My
Personal Information | Reset Security Token.
This is my code in my Console App:
static void Main(string[] args)
{
string userName;
string password;
userName = "me#myWebsite.com";
password = "myPassword";
SforceService SfdcBinding = null;
LoginResult CurrentLoginResult = null;
SfdcBinding = new SforceService();
try
{
CurrentLoginResult = SfdcBinding.login(userName, password);
}
catch (System.Web.Services.Protocols.SoapException e)
{
// This is likley to be caused by bad username or password
SfdcBinding = null;
throw (e);
}
catch (Exception e)
{
// This is something else, probably comminication
SfdcBinding = null;
throw (e);
}
}
The error states I need a security token, but the documentation never seems to mention it and I'm not sure how to get one.
What I had to do (which was not in the documentation) is go to here:
https://na15.salesforce.com/_ui/system/security/ResetApiTokenConfirm?retURL=%2Fui%2Fsetup%2FSetup%3Fsetupid%3DPersonalInfo&setupid=ResetApiToken
And, reset my token. Then, append it to the end of my password like:
If your password = "mypassword"
And your security token = "XXXXXXXXXX"
You must enter "mypasswordXXXXXXXXXX" in place of your password
Ref. http://docs.servicerocket.com/pages/viewpage.action?pageId=83099770
With a SOAP API like this you need to authenticate to the service first by providing the username and password. Their response should return an authorization token that will be valid for a period of time. Then in your subsequent communications you pass this token to the API so that it knows who you are.
Get the authorization token:
SforceService SfdcBinding = null;
LoginResult CurrentLoginResult = null;
SfdcBinding = new SforceService();
try
{
CurrentLoginResult = SfdcBinding.login(userName, password);
}
catch (System.Web.Services.Protocols.SoapException e)
{
// This is likely to be caused by bad username or password
SfdcBinding = null;
throw (e);
}
catch (Exception e)
{
// This is something else, probably communication
SfdcBinding = null;
throw (e);
}
Setup the session:
//Change the binding to the new endpoint
SfdcBinding.Url = CurrentLoginResult.serverUrl;
//Create a new session header object and set the session id to that returned by the login
SfdcBinding.SessionHeaderValue = new SessionHeader();
SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId;
Perform your query:
QueryResult queryResult = null;
String SOQL = "select FirstName, LastName, Phone from Lead where email = 'john.smith#salesforce.com'";
queryResult = SfdcBinding.query(SOQL);

ASP.NET Set cookie ONLY if empty Value

I am trying to set a cookie when the user access my webpage. The value of the cookie is a unique number that I store on my database to keep track of when the user comes back to my website. I set the cookie in my global.asax as follow:
void Application_BeginRequest()
{
string cookievalue = "";
string a = "";
try
{
a = GetCookie();
if (!string.IsNullOrEmpty(a))
{
cookievalue = a;
}
else
{
cookievalue = SetCookie();
}
}
catch (Exception ex)
{
}
}
In BeginRequest() I only want to check if the cookie exist. If exist, then do nothing and keep the value that is already inside the cookie. If it doesn't exist, then set the cookie and add a value.
public static string GetCookie()
{
string cookievalue = "";
try
{
if (HttpContext.Current.Request.Cookies["TestCookie"] != null)
cookievalue = HttpContext.Current.Response.Cookies["TestCookie"].Value;
}
catch (Exception ex)
{
//
}
return cookievalue;
}
public static string SetCookie()
{
string cookievalue = "";
try
{
HttpCookie myCookie = new HttpCookie("TestCookie");
// Set the cookie value.
myCookie.Value = "1234"; //1234 is my unique number
myCookie.Expires = DateTime.Now.AddYears(50);
HttpContext.Current.Response.Cookies.Add(myCookie);
cookievalue = id;
}
catch (Exception ex)
{
//
}
return cookievalue;
}
The problem is that everytime I reload the page, "TestCookie" gets rewritten with a new value. I have been reading the MSDN about how cookies are stored in ASP.NET and according to the instructions, the way it is supposed to work fine. I must be doing something wrong that I cannot see it. I had all this code inside a normal page e.g. test.aspx.cs to test it early but had the same result and decided to move it to the application level and see if that would make any difference but it did not :(.

Categories

Resources