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>
Related
When i created a profile and when i add items it always says not declared in the code behind!!
I tried to change the Framework of the project from Framework 4.0 to Framework 3.5 and it still didn't work.
It says FirstNamep , LastNamep are not declared .
And in the Web.config :
<profile defaultProvider="CustomProfileProvider" enabled="true">
<providers>
</providers>
<!-- Define the properties for Profile... -->
<properties>
<add name="FirstNamep" type="String" />
<add name="LastNamep" type="String" />
</properties>
</profile>
Behind the Code:
Profile.FirstNamep = FirstNameTextBox.Text
Profile.LastNamep = LastNameTextBox.Text
The properties are dynamically generated at runtime, which means you can't access them from code-behind. What you can do is access them from your .ASPX pages using a script block (if that works for you). Like this.
<%# Page Language="C#" %>
<script runat="server">
public void Page_Init()
{
Profile.FirstNamep = "some dood";
}
</script>
<div>Your name is <%= Profile.FirstNamep %></div>
It seems to be sort of "by design" that the Profile is available to .aspx pages, but not to the code behind.
If you've defined the default provider as CustomProfileProvider, then that has to be a class that inherits System.Web.Profile.ProfileProvider. Otherwise, you should use the default SQL profile provider.
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
</connectionStrings>
<membership>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
I am developing a Web Application using ASP.NET MVC 4 and I create a couple of custom MembershipProvider and RoleProvider like bellow:
# Custom MembershipProviders
<membership defaultProvider="myMembershipProvider">
<providers>
<clear />
<add name="myMembershipProvider" type="WebApp1.Business.Auth.MyMembershipProvider" />
<add name="adminMembershipProvider" type="WebApp1.Business.Auth.AdminMembershipProvider" />
</providers>
</membership>
# Custom RoleProviders
<roleManager enabled="true" defaultProvider="MyRoleProvider">
<providers>
<clear />
<add name="MyRoleProvider" type="WebApp1.Business.Auth.MyRoleProvider" />
<add name="AdminRoleProvider" type="WebApp1.Business.Auth.AdminRoleProvider" />
</providers>
</roleManager>
My intention is to create a custom AuthorizeAttribute called Logon that will use the "myMembershipProvider" and "MyRoleProvider"; and create another one called AdminLogon that will use "adminMembershipProvider" and "AdminRoleProvider".
The reason I am creating two custom AuthorizeAttributes is because I want to separate some methods that get the permissons of each role.
The question is, how can I set dynamically the default MembershipProvider and RoleProviders
inside both custom AuthorizeAttribute.
For example:
// Set the default MembershipProvider as adminMembershipProvider
// Set the default RoleProvidersas as AdminRoleProvider
[AdminLogon(Roles = "Administrador")]
public ActionResult Funcionarios()
{
return View();
}
// Set the default MembershipProvider as myMembershipProvider
// Set the default RoleProvidersas as MyRoleProvider
[Logon(Roles = "Administrador")]
public ActionResult Funcionarios()
{
return View();
}
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.
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" />
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>