Asp.net Membership password - asp.net

I am using sql server and custom database to store membership provider tables. In my webconfig file I decreased the password strength but members still needs to apply default password strength. The following is the webconfig settings
<membership>
<providers>
<add name = "AspNetSqlProvider"
type = "System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName = "LocalSqlServer"
enablePasswordRetrieval = "false"
enablePasswordReset = "true"
requiresQuestionAndAnswer = "true"
applicationName = "/"
requiresUniqueEmail = "false"
passwordFormat = "Hashed"
maxInvalidPasswordAttempts = "5"
minRequiredPasswordLength = "6"
minRequiredNonalphanumericCharacters = "0"
passwordAttemptWindow = "10"
passwordStrengthRegularExpression = "" />
</providers>
</membership>

You need to set your membership provider as the default provider. Otherwise it will use the membership provider defined in Machine.Config.
<membership defaultProvider="AspNetSqlProvider" userIsOnlineTimeWindow="30">
<providers>
<clear/>
<add name = "AspNetSqlProvider"
type = "System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName = "LocalSqlServer"
enablePasswordRetrieval = "false"
enablePasswordReset = "true"
requiresQuestionAndAnswer = "true"
applicationName = "/"
requiresUniqueEmail = "false"
passwordFormat = "Hashed"
maxInvalidPasswordAttempts = "5"
minRequiredPasswordLength = "6"
minRequiredNonalphanumericCharacters = "0"
passwordAttemptWindow = "10"
passwordStrengthRegularExpression = "" />
</providers>
</membership>

Related

Not working login with roles (web forms)

I want create a authentication module with 3 roles in asp.net web forms.
I created a simple database with one table user (id, login, password, role).
I have a 3 roles: user, user2 and admin.
I would like to users with specific roles were redirected to individual pages.
Login.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication6
{
public partial class Login : System.Web.UI.Page
{
static string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["dbtestConnectionStrings"].ConnectionString;
SqlConnection _connection= new SqlConnection(DatabaseConnectionString);
protected void Page_Load(object sender, EventArgs e) {
}
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
var comm = new SqlCommand("select * from user where login=#login and password=#password", _connection);
comm.Parameters.AddWithValue("#login", LoginUser.UserName);
comm.Parameters.AddWithValue("#password", LoginUser.Password);
_connection.Open();
var rd = comm.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
{
Session["UserName"] = rd["login"].ToString();
string role = rd["role"].ToString();
if (role == "user") Response.Redirect("User/User.aspx");
else if (role == "user2") Response.Redirect("User2/User.aspx");
else Response.Redirect("Admin/Admin.aspx");
}
}
else
{
LoginUser.FailureText = "ERROR";
}
}
catch (Exception exception)
{
Response.Write(exception.StackTrace);
}
}
}
}
Result:
web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
</system.webServer>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
<connectionStrings>
<add name="dbtestEntities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=ROG-KOMPUTER\SQLEXPRESS;initial catalog=dbtest;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
<add name="dbtestConnectionString" connectionString="Data Source=ROG-KOMPUTER\SQLEXPRESS;Initial Catalog=dbtest;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework"
providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Can see two flaws
User is a keyword and you are using that as a table name
When assigning parameter value you are specifiying #
try below code
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
SqlCommand comm = new SqlCommand("select login,role from [user] where login=#login and password=#password", _connection);
comm.Parameters.AddWithValue("#login", LoginUser.UserName);
comm.Parameters.AddWithValue("#password", LoginUser.Password);
_connection.Open();
SqlDataReader rd = comm.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
{
Session["UserName"] = rd[0].ToString();
string role = rd[1].ToString();
if (role == "user") Response.Redirect("User/User.aspx");
else if (role == "user2") Response.Redirect("User2/User.aspx");
else Response.Redirect("Admin/Admin.aspx");
}
}
else
{
LoginUser.FailureText = "ERROR";
}
rd.Close();
_connection.Close();
}
catch (Exception exception)
{
Response.Write(exception.StackTrace);
}
}
Its look like that:
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
var comm = new SqlCommand("select login,role from [user] where login=#login and password=#password", _connection);
comm.Parameters.AddWithValue("#login", LoginUser.UserName);
comm.Parameters.AddWithValue("#password", LoginUser.Password);
_connection.Open();
SqlDataReader rd = comm.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
{
Session["UserName"] = rd[0].ToString();
string role = rd[1].ToString();
if (role == "user") Response.Redirect("User/User.aspx");
else if (role == "user2") Response.Redirect("User2/User.aspx");
else Response.Redirect("Admin/Admin.aspx");
}
}
else
{
LoginUser.FailureText = "ERROR";
}
rd.Close();
_connection.Close();
}
catch (Exception exception)
{
Response.Write(exception.StackTrace);
Label1.Text = exception.Message;
}
}

How to get the session details from sql server database

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>

Uploaded website does not sent emails

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.

Change provider connectionstring of sessionState aspnet at runtime

in order to change the connection string of the providers in aspnet membership with
custom provider(nauckit) I use this:
var connectionStringField = Membership.Provider.GetType().GetField("m_connectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (connectionStringField != null)
connectionStringField.SetValue(Membership.Provider, connectionString);
var roleField = Roles.Provider.GetType().GetField("m_connectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (roleField != null)
roleField.SetValue(Roles.Provider, connectionString);
var profileField = ProfileManager.Provider.GetType().GetField("m_connectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (profileField != null)
profileField.SetValue(ProfileManager.Provider, connectionString);
Where connectionstring is the connectionstring I want.
But I cannot change for the sessionState.
My webconfig is like this:
<membership defaultProvider="PgMembershipProvider">
<providers>
<clear />
<add name="PgMembershipProvider" type="NauckIT.PostgreSQLProvider.PgMembershipProvider" connectionStringName="myConnection1" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" requiresUniqueEmail="false" maxInvalidPasswordAttempts="100" passwordFormat="Hashed" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="PgRoleProvider" cacheRolesInCookie="true" cookieName=".AspNetRoles" cookiePath="/" cookieProtection="All" cookieRequireSSL="false" cookieSlidingExpiration="true" createPersistentCookie="false" cookieTimeout="30" maxCachedResults="25">
<providers>
<clear />
<add name="PgRoleProvider" type="NauckIT.PostgreSQLProvider.PgRoleProvider" connectionStringName="myConnection1" />
</providers>
</roleManager>
<profile enabled="true" defaultProvider="PgProfileProvider">
<providers>
<clear />
<add name="PgProfileProvider" type="NauckIT.PostgreSQLProvider.PgProfileProvider" connectionStringName="myConnection1" />
</providers>
<properties>
<add name="property1" type="long"/>
</properties>
</profile>
<sessionState mode="Custom" customProvider="PgSessionStateStoreProvider">
<providers>
<clear />
<add name="PgSessionStateStoreProvider" type="NauckIT.PostgreSQLProvider.PgSessionStateStoreProvider" enableExpiredSessionAutoDeletion="true" expiredSessionAutoDeletionInterval="60000" enableSessionExpireCallback="false" connectionStringName="myConnection1" />
</providers>
</sessionState>
Any help?
Thanks!
Just call global.SetStore in any IHttpModule that you have on your website.
DAMN i'm so happy this worked.
Global.asax.cs:
private FieldInfo StorePrivateMemberInfo = typeof(SessionStateModule).GetField("_store", BindingFlags.Instance | BindingFlags.NonPublic);
public void SetStore()
{
var store = StorePrivateMemberInfo.GetValue(this.Modules["Session"]);
if (store == null || !(store is Microsoft.Web.SessionState.SqlInMemoryProvider))
{
var config = new NameValueCollection();
var cnn = "Your connection string";
config.Add("connectionString", cnn);
config.Add("timeout", "30");
simp = new Microsoft.Web.SessionState.SqlInMemoryProvider();
simp.Initialize("SqlInMemoryProvider", config);
StorePrivateMemberInfo.SetValue(this.Modules["Session"], simp);
}
Session["GLOBAL_ASAX_CHECK"] = true;
}

ReportViewer Showing empty in vs2010

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.

Resources