AspNet Role provider kicking in and it shouldn't be - asp.net

I'm getting this error:
Line 246: <roleManager>
Line 247: <providers>
Line 248: <add name="AspNetSqlRoleProvider" connectionStringName="LocalSqlServer" applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
Line 249: <add name="AspNetWindowsTokenRoleProvider" applicationName="/" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
Line 250: </providers>
Source File: C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config Line: 248
However, it shouldn't be as we're not using the aspnetroleprovider. But it's in the machine.config. Other sites don't have this problem. What could be making it pick up the aspnetsqlroleprovider?

fix
add enableSimpleMembership with value false app setting to your web.config.
cause
<roleManager enabled="false" />
will cause Roles.Enabled flag to be set to false, as expected,
but there is 'WebMatrix.WebData.WebSecurity' that says:
internal static void PreAppStartInit()
{
if (!ConfigUtil.SimpleMembershipEnabled)
return;
...
Roles.Enabled = true;
const string BuiltInRolesProviderName = "AspNetSqlRoleProvider";
var builtInRoles = Roles.Providers[BuiltInRolesProviderName];
if (builtInRoles != null)
{
var simpleRoles = CreateDefaultSimpleRoleProvider(BuiltInRolesProviderName, currentDefault: builtInRoles);
Roles.Providers.Remove(BuiltInRolesProviderName);
Roles.Providers.Add(simpleRoles);
}
...
}
this will override roleManager setting (this code is executed before RoleManager module is), including adding AspNetSqlRoleProvider
to disable 'SimpleMembership' you can add app setting enableSimpleMembership with value="false" (web.config):
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<appSettings>
<add key="enableSimpleMembership" value="false" />
</appSettings>
</configuration>
this will prevent webmatrix from reconfiguring RoleManager.

Add the <clear/> to your web.config's section of role providers. On this way you avoid inheriting if you don't use one. You should add it also for Membership and Profile providers section.
<roleManager>
<providers>
<clear/>
</providers>
....
Edit: Maybe you need to remove it explicitely:
<roleManager>
<providers>
<clear/>
<remove name="AspNetSqlRoleProvider" />
Another try:
Disable the role provider:
<system.web>
<roleManager enabled="false" />
</system.web>
http://msdn.microsoft.com/en-us/library/ms998314.aspx#paght000013_step2

Related

use location tag in web.config to remove settings for a child app

hi i am trying to run a child application inside a sub folder of my asp.net website. The web.config file of my child application inherits from the root web.config and will not compile when i try to access the path.
I would like to switch settings in the web.config depending on the path using
as this is how all the solutions i have read deal with this issue. Unfortunately they all use inheritInChildApplications which has been removed from .net 4
My web application project is named Dating and the folder that contains the child application is called Mobile
i have tried various combinations of the following in my root web.config
<location path="Mobile" allowOverride="true" >
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
</location>
<location path="." allowOverride="true">
<system.web>
<globalization culture="en-US" uiCulture="en" requestEncoding="UTF-8" responseEncoding="UTF-8" fileEncoding="UTF-8" />
<httpRuntime maxRequestLength="15360" requestLengthDiskThreshold="15360" requestValidationMode="2.0" />
<customErrors mode="Off" />
<trace localOnly="false" mostRecent="true" pageOutput="true" />
<compilation targetFramework="4.5" debug="true">
<assemblies>
<add assembly="AjaxControlToolkit" />
<add assembly="System.Web.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<roleManager enabled="true" defaultProvider="CustomizedRoleProvider">
<providers>
<add name="CustomizedRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="Dating" applicationName="Dating" />
</providers>
</roleManager>
<membership defaultProvider="CustomizedMembershipProvider">
<providers>
<add name="CustomizedMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="Dating" applicationName="Dating" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="15" minRequiredPasswordLength="1" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" />
</providers>
</membership>
<profile enabled="true" defaultProvider="YafProfileProvider" inherits="YAF.Utils.YafUserProfile">
<providers>
<clear />
<add connectionStringName="Dating" applicationName="Dating" name="YafProfileProvider" type="YAF.Providers.Profile.YafProfileProvider" />
</providers>
</profile>
<!--<profile inherits="Dating.WebProfile.UserProfile" enabled="true">
<providers>
<add name="CustomizedProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="Dating" applicationName="Dating"/>
</providers>
</profile>-->
<pages enableEventValidation="false" validateRequest="false" controlRenderingCompatibilityVersion="4.0">
<controls>
<!--<add assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagPrefix="ajx"/>-->
<!--<add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" /> -->
<add tagPrefix="ajx" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
<!-- Default: use non-dynamic (compiled classes) in YAF -->
<add tagPrefix="YAF" namespace="YAF.Controls" assembly="YAF.Controls" />
<add tagPrefix="YAF" namespace="YAF.Controls.Statistics" assembly="YAF.Controls" />
<add tagPrefix="YAF" namespace="YAF.Classes" />
<add tagPrefix="YAF" namespace="YAF" />
<add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
</controls>
<namespaces>
<add namespace="YAF.Core" />
<add namespace="YAF.Controls" />
<add namespace="YAF.Utils" />
<add namespace="YAF.Types.Interfaces" />
<add namespace="YAF.Types" />
</namespaces>
</pages>
</system.web>
</location>
i would like the settings taken from the mobile web.config to override the settings in the root but this does not appear to happen. i get the following error
Could not load file or assembly 'YAF.Core' or one of its dependencies. The system cannot find the file specified.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'YAF.Core' or one of its dependencies. The system cannot find the file specified.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Can anybody help?
having done lots of research I have found that the inheritance of web configs is very tricky.
This article is very helpful and sums up how this works very concisely
http://weblogs.asp.net/jgalloway/archive/2012/01/17/10-things-asp-net-developers-should-know-about-web-config-inheritance-and-overrides.aspx
I have decided the quickest solution for my problem is to setup the mvc app as a subdomain.
In future a good solution i think is to have a base site with no changes to the web.config. Then setup a descendant site from this to give you the option to setup a sibling site that does not inherit from any other descendant sites web.cofig but is still part of the same site.

Asp.net membership WebSecurity.InitializeDatabaseConnection error

When i'm trying to get to Web Site Administration Tool (WAT) (Project->ASP.NET Configuration in Visual Studio) i get following error
You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other >method of the "WebSecurity" class. This call should be placed in an _AppStart.cshtml file in >the root of your site.
And this is my connection string:
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|Database1.mdf;User Instance=true" providerName="System.Data.SqlClient" />
I've also enabled simple membership
<add key="enableSimpleMembership" value="true" />
My roleshipprivider config looks like this
<roleManager enabled="true" defaultProvider="MySqlRoleProvider">
<providers>
<clear />
<add connectionStringName="DefaultConnection" applicationName="/"
name="MySqlRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
And my membership conf
<membership defaultProvider="MyOwnSqlMembershipProvider">
<providers>
<clear/>
<add connectionStringName="DefaultConnection" enablePasswordRetrieval="false"
enablePasswordReset="true" requiresQuestionAndAnswer="false"
requiresUniqueEmail="true" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
name="MyOwnSqlMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
Does anybody know where's the bug?
Thanks in advance, Mateusz Urban
You should add the code below to Global.aspx.cs inside protected void Application_Start() and should appear at the top before any other registrations. This way, it will always be Initialized before an other operations.
if (!WebSecurity.Initialized)
WebSecurity.InitializeDatabaseConnection("DefaultConnection",
"UserProfile", "UserId", "UserName", autoCreateTables: true);
You need to include code to actually initialize the membership provider. The following in _AppStart.cshtml should work:
#{
if (!WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection("dbContext", "Users", "Id", "Login", autoCreateTables: false);
}
}

Enterprise Library 5.0 Logging in ASP.Net Webservice project - Activation error

I receive the following exception while attempting to log an error using Enterprise Library 5.0:
Activation error occured while trying to get instance of type LogWriter, key \"\""
Inner Exception Message 1:
"Resolution of the dependency failed,
type = \"Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter\",
name = \"(none)\".
Inner Exception Message 2:
The type LogWriter cannot be constructed.
You must configure the container to supply this value."
Here's the code:
public static void WriteException(Exception ex, string title)
{
try
{
LogEntry logEntry = new LogEntry()
{
Title = title,
Message = ex.Message,
Severity = TraceEventType.Error,
TimeStamp = DateTime.Now
};
Logger.Write(logEntry);
}
catch (Exception exception)
{
}
}
And here's my Web.config:
<?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>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true"/>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true"/>
</configSections>
<dataConfiguration defaultDatabase="OracleConnection">
<providerMappings>
<add databaseType="Microsoft.Practices.EnterpriseLibrary.Data.Oracle.OracleDatabase, Microsoft.Practices.EnterpriseLibrary.Data" name="Oracle.DataAccess.Client"/>
</providerMappings>
</dataConfiguration>
<connectionStrings>
<add name="PortalAdminContext" connectionString="Data Source=|DataDirectory|PortalAdmin.sdf" providerName="System.Data.SqlServerCe.4.0"/>
<add name="OracleConnection" connectionString="" providerName="Oracle.DataAccess.Client"/>
<add name="PersonalizationConnection" connectionString="" providerName="Oracle.DataAccess.Client"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<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>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0"/>
<add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
</DbProviderFactories>
</system.data>
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
<listeners>
<add name="Event Log Listener"
type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
source="PortalWebservice"
formatter="Text Formatter"
log="Portal"
machineName="."
traceOutputOptions="DateTime, Timestamp"
filter="All"/>
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
template="Timestamp: {timestamp}{newline}
Message: {message}{newline}
Severity: {severity}{newline}
Title:{title}{newline}"
name="Text Formatter"/>
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Event Log Listener"/>
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events">
<listeners>
<add name="Event Log Listener"/>
</listeners>
</allEvents>
<notProcessed switchValue="All" name="Unprocessed Category">
<listeners>
<add name="Event Log Listener"/>
</listeners>
</notProcessed>
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Event Log Listener"/>
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
</configuration>
The "Portal" event log has been created.
This same code and same configuration work fine in other projects. However, I received the activation error in an ASP .Net Webservice, while attempting to log. It seems like it can't find the Web.config when attempting to create the LogWriter.
I noticed that other projects started to experience the same "Activation Error" with the Database portion of Enterprise Library, and more investigation lead me to the machine.config for the .Net Framework 2.0 & 3.5. There was a common entry in machine.config and the project's web.config for the Oracle Data Provider. Adding the entries that follow to web.config corrected the "Activation Errors" in the other projects and corrected the LogWriter Activation error in the project mentioned above:
<system.data>
<DbProviderFactories>
<remove invariant="Oracle.DataAccess.Client"/>
<add name="Oracle Data Provider for .NET" invariant="Oracle.DataAccess.Client" description="Oracle Data Provider for .NET" type="Oracle.DataAccess.Client.OracleClientFactory, Oracle.DataAccess, Version=2.102.2.20, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
</DbProviderFactories>
</system.data>

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.

Membership Role Provider doesn't work with custom connection string?

plz help with one issue.
I have Membership configured with IIS7, tables for it located in my own database, created with aspnet_regsql utility, and I am using custom connection string to access it.
This is part of web.config related to Membership :
<connectionStrings>
<add connectionString="Server=CORESERVER\SQLExpress;Database=Shop;User ID=Tema;Password=Matrix" name="CustomSqlConnection" />
</connectionStrings>
<profile enabled="true">
<providers>
<add name="CustomSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="CustomSqlConnection" />
</providers>
</profile>
<roleManager defaultProvider="AspNetSqlRoleProvider" enabled="true">
<providers>
<add name="CustomSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="CustomSqlConnection" />
</providers>
</roleManager>
<membership defaultProvider="CustomSqlMemberProvider">
<providers>
<add name="CustomSqlMemberProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="CustomSqlConnection" enablePasswordReset="true" enablePasswordRetrieval="false" passwordFormat="Hashed" requiresQuestionAndAnswer="true" requiresUniqueEmail="true" applicationName="/" maxInvalidPasswordAttempts="10" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
</providers>
</membership>
<authentication mode="Forms">
<forms cookieless="UseCookies" loginUrl="login.aspx" name="WebShopAuthentication" protection="All" timeout="30" path="/" requireSSL="false" defaultUrl="~/admin/default.aspx" />
</authentication>
<authorization>
<allow users="*" />
</authorization>
And ... Forms authorization, getting user and his membership info is OK.
But ... getting roles is always FALSE.
MembershipUser userData = Membership.GetUser(HttpContext.Current.User.Identity.Name); // OK !!! IT IS GREAT :)
var a = new RolePrincipal(HttpContext.Current.User.Identity);
var aa = a.getRoles(); // {string[0]} - EMPTY!!!
var b = Roles.IsUserInRole("Administrator", "Administrator"); // FALSE!!!
var c = Roles.Providers["CustomSqlRoleProvider"].GetAllRoles(); // {string[0]} - EMPTY!!!
var d = Roles.IsUserInRole(HttpContext.Current.User.Identity.Name, "Administrator"); // FALSE!!!
var e = HttpContext.Current.User.IsInRole("Administrator"); // FALSE !!!
WHYYYY???
What am i doing wrong???
Just to refine ... authorization works fine and uses roles correctly. Another part of my web.config :
<location path="Admin">
<system.web>
<pages styleSheetTheme="Admin" theme="Admin">
</pages>
<authorization>
<deny users="?" />
<allow roles="Administrator" />
</authorization>
</system.web>
<appSettings>
<add key="ThemeName" value="Admin" />
</appSettings>
</location>
And then in code is used :
Membership.ValidateUser(userName.Text, userPassword.Text) // AND IT WORKS - USER IS LOGGED IN
The answer is that i didn't add applicationName parameter to web.config correctly - after adding i should restart IIS and if needed recreate roles.
This is final version of web.config :
<roleManager defaultProvider="CustomSqlRoleProvider" enabled="true">
<providers>
<add name="CustomSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="CustomSqlConnection" applicationName="/" />
</providers>
</roleManager>

Resources