I have a website in which I am migrating membership from ASP.NET services to a custom provider. I would like to migrate existing users without them needing to change their passwords.
The users' passwords are currently stored using a one-way encryption. The only option for me is to use the same salt and passwords as the ASP services and validate against them with my custom provider.
Here is the configuration used to currently hash the passwords with ASP.NET services.
<membership defaultProvider="AspNetSqlMembershipProvider" userIsOnlineTimeWindow="15" hashAlgorithmType="">
<providers>
<clear/>
<add connectionStringName="dashCommerce" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="dashCommerce" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" passwordAttemptWindow="10" passwordStrengthRegularExpression="" minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0" name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</providers>
</membership>
I have been pulling my hair out trying to write the code needed to validate passwords against hashes generated by this config.
This is what I have so far. Any help would be greatly appreciated.
private static string CreatePasswordHash(string Password, string Salt)
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(Password + Salt, "SHA1");
}
//string hashOldPassword = utl.generateHash(txtpassword.Text);
string hashOldPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(txtpassword.Text,"SHA1");
//string hashOldPassword = Membership.Provider.GetPassword(Page.User.Identity.Name.ToString(), string.Empty);
MembershipUser user = Membership.GetUser();
//string hashOldPassword = user.GetHashCode(
if (txtnewpassword.Text.Length < 7)
{
}
var userId = user.ProviderUserKey;
var user1 = Membership.GetUser();
MembershipPasswordFormat passwordFormat;
string passwordSalt;
string password;
SqlConnection sqlconn = new SqlConnection(Connect.Connection());
//var cstring = ConnectionStrings[Connect.Connection()];
using (var conn = new SqlConnection(sqlconn.ConnectionString))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "select PasswordFormat,PasswordSalt,Password from aspnet_Membership where UserId=#UserId";
cmd.Parameters.AddWithValue("#UserId", userId);
conn.Open();
using (var rdr = cmd.ExecuteReader())
{
if (rdr != null && rdr.Read())
{
passwordFormat = (MembershipPasswordFormat)rdr.GetInt32(0);
// passwordFormat = rdr.GetString(0);
passwordSalt = rdr.GetString(1);
password = rdr.GetString(2);
if (hashOldPassword == password)
{
user.ChangePassword(txtpassword.Text, txtnewpassword.Text);
}
else
{
}
//if(password.ToString()!=txtpassword)
}
else
{
throw new Exception("An unhandled exception of type 'DoesntWorkException' has occured");
}
}
I dug through reflector and found the code used to compute hashes.
private static string CreatePasswordHash(string Password, string Salt)
{
string passwordFormat = SettingManager.GetSettingValue("Security.PasswordFormat");
if (String.IsNullOrEmpty(passwordFormat))
passwordFormat = "SHA1";
byte[] bytes = Encoding.Unicode.GetBytes(Password);
byte[] src = Convert.FromBase64String(Salt);
byte[] dst = new byte[src.Length + bytes.Length];
byte[] inArray = null;
Buffer.BlockCopy(src, 0, dst, 0, src.Length);
Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
HashAlgorithm algorithm = HashAlgorithm.Create(passwordFormat);
inArray = algorithm.ComputeHash(dst);
return Convert.ToBase64String(inArray);
}
This worked.
Related
I'm using $http.get to connect to an asmx webservice passing 2 parameters: username and password. However it returns the html page of the web service instead of data.
am I missing something?
here's my code for controller.js:
$scope.enterlogin = function(usern,pass)
{
loginService.getUser(usern,pass).then(function(response){
console.log('response is = ' + response.data);
};
}
Here's my code for services.js:
.factory('loginService', ['$http', function($http){
var base_url = "http://<ipaddress of webservie>/UserService3/WebService1.asmx?op=getUserbyUsername";
return {
getUser: function(usern,pass){
console.log('code side usern is = ' + usern + "" + pass);
return $http.get(base_url, { params: { passw: pass, uname: usern}
});
}
}
}])
I also added these to the webservice's web.config file:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
<httpHandlers>
<add verb="GET,HEAD,POST,OPTIONS" path="*.asmx" type="System.Web.UI.PageHandlerFactory" />
</httpHandlers>
And this:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
and this is the webmethod in the webservice:
[WebMethod]
public string getUserbyUsername(string uname, string passw)
{
string cs = "Data Source =.; Initial Catalog = UsersDB; Integrated Security = True";
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetUserByUsername", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter(#"Username", uname);
SqlParameter parameter2 = new SqlParameter(#"Password", passw);
cmd.Parameters.Add(parameter);
cmd.Parameters.Add(parameter2);
User user = new User();
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// user.Username = reader["Username"].ToString();
// user.Password = reader["Password"].ToString();
user.IsExisting = reader["IsExisting"].ToString();
user.UserID = reader["UserID"].ToString();
}
con.Close();
return new JavaScriptSerializer().Serialize(user);
}
}
You might need to change System.Web.UI.PageHandlerFactory (which is typically used for aspx endpoints) to System.Web.Services.Protocols.WebServiceHandlerFactory (which is more typically used for asmx endpoints).
EDIT: try changing the return to void and then doing this:
Context.Response.Write(new JavaScriptSerializer().Serialize(user));
See if that works.
I have one Solution which has different projects like ASP.Net
and ASP.Net MVC in this solution. When the user logs in to the
application, the same credentials I need to pass to the other project
in same solution. It should not ask credentials again, because he has
already logged in. For that I have stored the session details in the sql
server database using the SqlServer mode. But the problem is I am unable
to get the session which is stored in the database.
Any help on this will be appreciated. Thanks in advance.
This is what i have tried to fetch data from ASPState database
public ActionResult Home()
{
ViewBag.Result =Session["username"].ToString();
SqlCommand cmd = new SqlCommand("select SessionId from
ASPStateTempSessions", con);
byte[] bytdata = new byte[50];
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
var list = new List<LoginUser>();
if(dr.HasRows)
{
while(dr.Read())
{
//obj=dr["SessionId"];
string obj = dr["SessionId"].ToString();
bytdata = System.Text.Encoding.UTF8.GetBytes(obj);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytdata);
BinaryFormatter bin = new BinaryFormatter();
//bin.Serialize(ms, bytdata);
//list = (List<LoginUser>)bin.Deserialize(ms);
string session = Convert.ToString(bin.Deserialize(ms));
}
}
ViewBag.Data = list;
return View();
}
This is what i have configured ion Web.config
<sessionState mode="SQLServer" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="SessionSqlCon" cookieless="false" timeout="10" />
</providers>
</sessionState>
I have uploaded my website to a known hosting server and i have a contact form, the weird thing is that when i run the website from visual studio (asp.net language) is sending the emails fine on my inbox.From the time that i uploaded it on the hosting server it gives the error: failure sending the email.I am using smtp.gmail.com, port:587,username and pass and ssl enabled.
protected void sendClientMail(string emailto)
{
try
{
var mail = new MailMessage
{
BodyEncoding = Encoding.UTF8,
From = new MailAddress(ConfigurationManager.AppSettings["MAILFROM"])
};
mail.To.Add(emailto);
mail.Bcc.Add(ConfigurationManager.AppSettings["MAILBCC"]); //sends to my email also
mail.Subject=ConfigurationManager.AppSettings["CLIENT-MAILSUBJECT"];
mail.IsBodyHtml = true;
#region //Load Email Control and get HTML string
string mailBody = "";
{
PrintPlaceHolder.Visible = true;
var sb = new StringBuilder();
var writer = new HtmlTextWriter(new StringWriter(sb));
var emailctl = LoadControl("~/Controls/ClientEmail.ascx") as ClientEmail;
if (emailctl != null)
{
emailctl.Name = txtName.Text;
emailctl.IntroName = txtName.Text + " " + txtSurname.Text;
emailctl.Surname = txtSurname.Text;
emailctl.Mobile = txtMobile.Text;
emailctl.Phone = txtPhone.Text;
emailctl.City = txtCity.Text;
emailctl.Street = txtStreet.Text;
emailctl.Message = txtmessage.Text;
emailctl.Email = txtEmail.Text;
emailctl.Country = ddlCountry.SelectedValue;
PrintPlaceHolder.Controls.Add(emailctl);
emailctl.RenderControl(writer);
}
mailBody = sb.ToString();
if (emailctl != null)
{
emailctl.Dispose();
}
writer.Dispose();
sb.Clear();
PrintPlaceHolder.Visible = false;
}
#endregion
mail.Body = mailBody;
//mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential (ConfigurationManager.AppSettings["MAILFROM"], ConfigurationManager.AppSettings["PASS"]);
client.Host = ConfigurationManager.AppSettings["SMTPSERVER"];
client.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPORT"]);
//client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl= false;
//client.UseDefaultCredentials = true;
client.Send(mail);
clearFields();
Response.Write("<script>alert('"+ConfigurationManager.AppSettings["MAILSUCCESS"]+"');</script>");
}
catch (Exception e)
{
Response.Write("<script>alert('"+ ConfigurationManager.AppSettings["MAILFAIL"] +" Error: "+e+"')</script>");
}
}//end method
Web.config file code:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
<add key="CLIENT-MAILSUBJECT" value="Mario Website - Confirmation Email"/>
<add key="MY-MAILSUBJECT" value="Mario Website - Email Sent"/>
<add key="MAILFROM" value="mariotec#mario26tech.com"/>
<add key="MAILBCC" value="nikolaou_marios#hotmail.com"/>
<add key="SMTPSERVER" value="sns41.win.hostgator.com"/>
<add key="SMTPPORT" value="26"/>
<add key="PASS" value="pass"/>
<add key="MAILSUCCESS" value="Email was sent successfully, thank you for your interest!!!"/>
<add key="MAILFAIL" value="There was an error while sending the email."/>
</appSettings>
<system.webServer>
<defaultDocument enabled="true">
<files>
<clear/>
<add value="Index.aspx"/>
</files>
</defaultDocument>
</system.webServer>
</configuration>
I have contacted the hosting provider without any help.
Thanks in advance.
I'm calling a report from report server, the project runs successfully but the page will be empty. through development tool I can find the amount of space it is acquired.
Below is the code i'm using.
Web Config.
under system.web
<httpHandlers>
<add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="false"/>
</httpHandlers>
system.web under compilation
<buildProviders>
<add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.Common, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</buildProviders>
and there are some assemblies which are automatically added when the reportviewer was added to the page.
under system.webservices
<handlers>
<add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</handlers>
cs page
int dcid = 1;
ReportViewer1.Visible = true;
ReportViewer1.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
ReportViewer1.ServerReport.ReportServerUrl = new Uri(ConfigurationManager.AppSettings["ReportServer"].ToString());
Microsoft.Reporting.WebForms.ReportParameterInfoCollection paramInfo;
System.Collections.Generic.List<Microsoft.Reporting.WebForms.ReportParameter> paramList = new System.Collections.Generic.List<Microsoft.Reporting.WebForms.ReportParameter>();
paramList.Add(new Microsoft.Reporting.WebForms.ReportParameter("DCId", dcid.ToString(), false));
ReportViewer1.ServerReport.ReportPath = ConfigurationManager.AppSettings["ReportsFolder"].ToString() + "rpt_DCForm";
ReportViewer1.ServerReport.ReportServerCredentials = new Credentials(ConfigurationManager
.AppSettings["ReportUserName"].ToString(), ConfigurationManager
.AppSettings["ReportUserPwd"].ToString(), ConfigurationManager
.AppSettings["ReportserverDomain"].ToString());
ReportViewer1.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Local;
ReportViewer1.ServerReport.SetParameters(paramList);
paramInfo = ReportViewer1.ServerReport.GetParameters();
ReportViewer1.ServerReport.Refresh();
Credentials class
string _userName, _password, _domain;
public Credentials(string userName, string Password, string domain)
{
_userName = userName;
_password = Password;
_domain = domain;
}
#region IReportServerCredentials Members
public bool GetFormsCredentials(out System.Net.Cookie authCookie, out string userName, out string password, out string authority)
{
//userName = _userName;
//password = _password;
//authority = _domain;
//authCookie = new System.Net.Cookie(".ASPXAUTH", ".ASPXAUTH", "/", "Domain");
//return true;
authCookie = null;
userName = password = authority = null;
return false;
}
public System.Security.Principal.WindowsIdentity ImpersonationUser
{
get { return null; }
}
public System.Net.ICredentials NetworkCredentials
{
get { return new System.Net.NetworkCredential(_userName, _password, _domain); }
}
#endregion
The same code works fine in our other project. For a new solution Its not working.
Please help what I'm missing out.
Thanks in advance.
I am developing VS2010. this is my problem:I have a Form that authenticate user and then redirect them to another page .the redirection is not working If I write username and password system say nothing and two textboxes being empty :
here is a part of my login control
<asp:Login ID="LoginUser" runat="server" EnableViewState="false"
RenderOuterTable="false" DestinationPageUrl="~/verwaltung.aspx" MembershipProvider="AspNetSqlMembershipProvider">
and also in my web.config I have:
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
</providers>
</membership>
how can I solve this problem?
You said your codebehind is empty, actually when you use login control you need to write login handler like this.
protected void Login1_Authenticate1(object sender, AuthenticateEventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Online"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT FirstName, LastName FROM Account WHERE Username=#Username AND Password=#Password", conn);
SqlDataReader rdr = null;
SqlParameter Username = new SqlParameter();
Username.SqlDbType = SqlDbType.VarChar;
Username.ParameterName = "Username";
Username.Value = Login1.UserName.ToString().ToLower().Trim();
SqlParameter Password = new SqlParameter();
Password.SqlDbType = SqlDbType.VarChar;
Password.ParameterName = "Password";
Password.Value = Login1.Password;
cmd.Parameters.Add(Username);
cmd.Parameters.Add(Password);
try
{
conn.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
e.Authenticated = true;//User was found in the database
Session["Username"] = Login1.UserName.ToString();
Session["Name"] = rdr[0].ToString() + " " + (rdr[1].ToString() == null ? "" : rdr[1]);
}
}
finally
{
if (conn != null)
conn.Close();
if (rdr != null)
rdr.Close();
if (e.Authenticated)
Response.Redirect("profile.aspx");//Do whatever needs to be done when user gets authenticated
}
}