How to manually verify a user against the ASP.NET memberhip database? - asp.net

I would like to know how I can verify a user's credential against an existing asp.net membership database. The short story is that we want provide single sign on access.
So what I've done is to connect directly to the membership database and tried to run a sql query against the aspnet_Membership table:
private bool CanLogin(string userName, string password)
{
// Check DB to see if the credential is correct
try
{
string passwordHash = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");
string sql = string.Format("select 1 from aspnet_Users a inner join aspnet_Membership b on a.UserId = b.UserId and a.applicationid = b.applicationid where a.username = '{0}' and b.password='{1}'", userName.ToLowerInvariant(), passwordHash);
using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString))
using (SqlCommand sqlCmd = new SqlCommand(sql, sqlConn))
{
sqlConn.Open();
int count = sqlCmd.ExecuteNonQuery();
return count == 1;
}
}
catch (Exception ex)
{
return false;
}
}
The problem is the password value, does anyone know how the password it is hashed?

if you have two asp.net apps on the same IIS server, you can do SSO like this. I asked this question and answered it myself.
here
Once you have both apps pointing at your asp_membership database by placing the following in the system.web section of your web config
<authentication mode="Forms" />
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="membership"
applicationName="/"
/>
</providers>
</membership>
<roleManager enabled="true" />
make sure both have the same applicationname property set.
I was using IIS 6 so I configured it to autogenerate a machine key for both applications. Because both of these applications live on the same machine the key would be identical, this is the critical part to making the SSO work. After setting up IIS the following was added to my web.config
<machineKey decryptionKey="AutoGenerate" validation="SHA1" validationKey="AutoGenerate" />
That was all there was to it. Once that was done I could log into app1 and then browse to app2 and keep my security credentials.

The problem is the password value,
does anyone know how the password it
is hashed?
Yes - you do! Check your web.config file for something like this:
<membership defaultProvider="MembershipSqlProvider"
userIsOnlineTimeWindow="15">
<providers>
<add name="MembershipSqlProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web,
Version=1.2.3400.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
PasswordFormat="Hashed" />
</providers>
</membership>
The PasswordFormat is what you are looking for. It can have the following three values:
Clear
Encrypted
Hashed
And, Microsoft sets the default value to Hashed for PasswordFormat.

Why don't check it automatically via System.Web.Security.Membership.ValidateUser() ?
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<membership defaultProvider="MyMembershipProvider">
<providers>
<clear />
<add name="MyMembershipProvider" type="MyApplication.MyMembershipProvider" connectionStringName="MyConnString" />
</providers>
</membership>
</system.web>
</configuration>

Related

mySQL asp role provider error. Unable to connect to SQL Server database

This is my first attempt at doing roles for asp.net, what I have is a mySQL backend, and I want to add a bunch of roles to a user. The code i'm using below, i keep getting the error Unable to connect to SQL Server database. I'm assuming this is because the default provider refers to SQL, but i'm not able to figure out how to switch it so I can add multiple roles to a user. Thanks for the help!
using (MySqlConnection cn2 = new MySqlConnection("Server=localhost;Database=users; User=root;Password=PASSWORD;"))
{
cn2.Open();
MySqlCommand cmd2 = new MySqlCommand(storedProcedureName2, cn);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.Add("#usernameID", userID);
MySqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
string roleName = dr2["role"].ToString();
Roles.AddUserToRole(userID, roleName);
}
}
You can configure the ASP.NET Membership and roles in the web.config file. Something like this would set your default provider to a MySQL backend:
<membership defaultProvider="MySqlMembershipProvider">
<providers>
<clear />
<add name="MySqlMembershipProvider" type="MySql.Web.Security.MySqlMembershipProvider,M ySql.Web,Version=6.3.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" autogenerateschema="true" connectionStringName="LocalMySqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requireQuestionAndAnswer="false" requireUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="0" passwordStrengthRegularExpression="" applicationName="/" />
</providers>
</membership>
<profile defaultProvider="MySqlProfileProvider">
<providers>
<clear/>
<add name="MySqlProfileProvider" type="MySql.Web.Profile.MySQLProfileProvider, MySql.Web, Version=6.3.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" conectionStringName="LocalMySqlServer" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="true" defaultProvider="MySqlRoleProvider">
<providers>
<clear/>
<add connectionStringName="LocalMySqlServer" applicationName="/" name="MySqlRoleProvider"
type="MySql.Web.Security.MySQLRoleProvider, MySql.Web, Version=6.3.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
</providers>
</roleManager>
<trust level="Full"/>
<machineKey validationKey="AutoGenerate" validation="SHA1"/>
EDIT: I added the connectionStrings section below:
<connectionStrings>
<remove name="LocalMySqlServer"/>
<add name="LocalMySqlServer" connectionString="Server=localhost;Database=users; User=root;Password=PASSWORD;" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
Try the following as the connection string:
"Server=localhost;Port=3306;Database=users;Uid=root;Pwd=PASSWORD;"
And if it works, change the password :)
If this doesn't work, and assuming the error is in the connecting ot the database (you confused my by publishing so many lines of code) do the usual checks:
Is the server running?
Is the password correct
Is the port default (3306)
Are there internal firewall issues, as MySQL uses TCP:3306 and in theory firewall can block this.

ASP.NET Role Manager Feature Has Not Been Enabled

I'm trying to create a routine in my asp.net's main page that will see if the current user is a member of a Windows domain group. The site is hosted in IIS and is visible through our intranet.
GlenFerrieLive listed this code (which I'd like to use) in an earlier post:
UserName = System.Environment.UserName
If Roles.IsUserInRole(UserName, "MyDomain\MyGroup") Then
Dim UserExists As Boolean = True
End If
When trying that code, I got the above-mentioned error. So I plugged in the roleManager tag in my Web.config like so:
<roleManager enabled="true" cacheRolesInCookie="true" defaultProvider="ActiveDirectoryMembershipProvider" cookieName=".ASPXROLES" cookiePath="/" cookieTimeout="480" cookieRequireSSL="false" cookieSlidingExpiration="true" createPersistentCookie="false" cookieProtection="All" />
Problem is, now I'm getting the configuration error 'Default Role Provider could not be found'.
How can I get around this? I just need to see if the current user exists in a specific domain group.
Any help would be greatly appreciated.
Thanks,
Jason
Look into this page:http://msdn.microsoft.com/en-us/library/ff648345.aspx
You need something like this in your webconfig specifying where the default role provider points to
<connectionStrings>
<add name="ADConnectionString"
connectionString=
"LDAP://domain.testing.com/CN=Users,DC=domain,DC=testing,DC=com" />
</connectionStrings>
<system.web>
...
<membership defaultProvider="MembershipADProvider">
<providers>
<add
name="MembershipADProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ADConnectionString"
connectionUsername="<domainName>\administrator"
connectionPassword="password"/>
</providers>
</membership>
...
</system.web>
I ended up using this:
Private Function ValidateActiveDirectoryLogin(ByVal Domain As String, ByVal Username As String, ByVal Password As String) As Boolean
Dim Success As Boolean = False
Dim Entry As New System.DirectoryServices.DirectoryEntry("LDAP://" & Domain, Username, Password)
Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
Searcher.SearchScope = DirectoryServices.SearchScope.OneLevel
Try
Dim Results As System.DirectoryServices.SearchResult = Searcher.FindOne
Success = Not (Results Is Nothing)
Catch
Success = False
End Try
Return Success
End Function
Worked like a charm when this was in my web.config:
<authentication mode="Windows"/>
<roleManager enabled="true" cacheRolesInCookie="true" defaultProvider="AspNetWindowsTokenRoleProvider" cookieName=".ASPXROLES" cookiePath="/" cookieTimeout="480" cookieRequireSSL="false" cookieSlidingExpiration="true" createPersistentCookie="false" cookieProtection="All" />

asp.net membership ResetPassword does not work

when i want to use ResetPassword method in vb.net or c# , it can not reset password and make an exeption that say : "The password-answer supplied is wrong".
i think it is caused by hashing system and machine code of hash and salt.
how can i solve this problem ?
add following attribute to your membership cofig section in your Web.Config file.
requiresQuestionAndAnswer="false"
full example
<configuration>
<connectionStrings>
<add name="SqlServices"
connectionString="Data Source=MySqlServer;Integrated Security=SSPI;Initial
Catalog=aspnetdb;" />
</connectionStrings>
<system.web>
<membership
defaultProvider="SqlProvider"
userIsOnlineTimeWindow="20">
<providers>
<remove name="AspNetSqlProvider" />
<add name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="SqlServices"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
passwordFormat="Hashed"
applicationName="/" />
</providers>
</membership>
</system.web>
</configuration>
I used it in a wrong way, and got the same error, hope helps you too. This is my code:
MembershipUser mu = Membership.GetUser(c.Username);
if (mu.PasswordQuestion == c.Question)
{
string pwd = mu.ResetPassword(c.Answer);
mu.ChangePassword(pwd, c.Password);
return RedirectToAction("SignIn");
}
else
{
ViewBag.Message = "Error!";
return View();
}

ASP.Net Using the Membership.CreateUser Method

I'm having issues using the membership.createuser method. My code is below, I get a null exception as runtime. Any help is greatly appreciated.
Dim username As String = userNameTxt.Text
Dim password As String = passwordTxt.Text
Dim email As String = emailTxt.Text
Dim status As New MembershipCreateStatus
Dim blank As String = ""
Dim provider As MembershipProvider
Dim providerUserKey As New System.Object
Dim user As MembershipUser
user = provider.CreateUser(username, password, email, blank, blank, True, providerUserKey, status)
you need concrete implementation of MembershipProvider abstract class
you can either create your own or use existing one. You also need to set it in web.config:
<connectionStrings>
<add name="MySqlConnection" connectionString="Data Source=MySqlServer;Initial Catalog=aspnetdb;Integrated Security=SSPI;" />
</connectionStrings>
<system.web>
...
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add
name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="MySqlConnection"
applicationName="MyApplication"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="true"
passwordFormat="Hashed" />
</providers>
</membership>
http://msdn.microsoft.com/en-us/library/ff648345.aspx
then you can use Membership.CreateUser, no need to create instance, it's static
it has also a property for default membership provider set in web.config: Membership.Provider
Use the shared methods on the Membership class. You will have to configure the membership provider to use in your web.config file.
Then it's simply:
Membership.CreateUser(username, password, email, blank, blank, True, providerUserKey, status)
For details on how to configure your membership provider, refer to msdn Memberhip doc
Dim provider As MembershipProvider
then
provider.CreateUser(..
provider is null as you haven't actually created a new instance
you should be using
System.Web.Security.Membership.CreateUser

Default SqlRoleProvider in backend code

How do I access the default SqlProvider in a DAL? I've only ever done this before from webforms.
With the following
using System.Web.Security;
....
SqlRoleProvider roleProvider = new SqlRoleProvider();
string[] roles = roleProvider.GetAllRoles(); //for example to get all role names
EDIT
To configure your application to use the SqlRoleProvider you'll need to add the following under the <system.web> section of your web.config file.
<roleManager enabled="true" defaultProvider="SqlRoleManager">
<providers>
<add name="SqlRoleManager"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="MyConnectionStringName" //change this to the name of your connection string
applicationName="MyApplication" />
</providers>
</roleManager>

Resources