VB.Net Forms Authentication - Roles.CreateRole()

0

So I recently started moving my applications over to a more secure authentication system for my un-managed users. I saw Forms authentication for VB.Net and had no issues getting started. I got two new users created and logged in with working password resets.

I just tried to use the Roles.CreateRole function to create a simple role and it through an error associated with app_data permissions.

I have already tried the excessive 50+ articles of people deleting the SQL folder in APP_Data from the windows XP days but it doesn't work for me. I tried looking for the readme file the error references but with over 400+ readmes in the Visual Studio file I'm lost on finding that information. I have also tried changing the IIS application pool identity to a local user and restarted the whole PC.

If anyone knows where the readme this error references is I would be more than happy to read that first.

Here is the sub where I try to run my code that throws the error when I call Roles.CreateRole

        Protected Sub gvUsers_RowCommand(sender As Object, e As GridViewCommandEventArgs)
        Dim strUsername = CType(sender, GridView).Rows(e.CommandArgument).Cells(0).Text
        Dim intLevel = Convert.ToInt16(CType(sender, GridView).Rows(e.CommandArgument).Cells(1).Text)
        Dim objMembers = Membership.FindUsersByName(strUsername)
        Dim objUser As MembershipUser = objMembers(strUsername)

        If e.CommandName = "Reset Password" Then
            lblError.Text = "Reset password for: <b>" & strUsername & "</b> New Password: <b>" & objUser.ResetPassword() & "</b>"
        ElseIf e.CommandName = "Delete" Then
            lblError.Text = "Deletion request for user: <b>" & strUsername & "</b> resulted in a <b>" & Membership.DeleteUser(strUsername).ToString & "</b> result."
        ElseIf e.CommandName = "Increase" Then
            Roles.CreateRole("MoldMaintAdmin")
            Roles.AddUserToRole(strUsername, "MoldMaintAdmin")
        ElseIf e.CommandName = "Decrease" Then
            Roles.CreateRole("MoldMaintUser")
            Roles.AddUserToRole(strUsername, "MoldMaintUser")
        End If

    End Sub

Here is the error in detail.

Server Error in '/' Application.
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.
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.

SQLExpress database file auto-creation error:

The connection string specifies a local Sql Server Express instance using a database location within the application's App_Data directory. The provider attempted to automatically create the application services database because the provider determined that the database does not exist. The following configuration requirements are necessary to successfully check for existence of the application services database and automatically create the application services database:

If the application is running on either Windows 7 or Windows Server 2008R2, special configuration steps are necessary to enable automatic creation of the provider database. Additional information is available at: http://go.microsoft.com/fwlink/?LinkId=160102. If the application's App_Data directory does not already exist, the web server account must have read and write access to the application's directory. This is necessary because the web server account will automatically create the App_Data directory if it does not already exist.
If the application's App_Data directory already exists, the web server account only requires read and write access to the application's App_Data directory. This is necessary because the web server account will attempt to verify that the Sql Server Express database already exists within the application's App_Data directory. Revoking read access on the App_Data directory from the web server account will prevent the provider from correctly determining if the Sql Server Express database already exists. This will cause an error when the provider attempts to create a duplicate of an already existing database. Write access is required because the web server account's credentials are used when creating the new database.
Sql Server Express must be installed on the machine.
The process identity for the web server account must have a local user profile. See the readme document for details on how to create a local user profile for both machine and domain accounts.


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.

Stack Trace:


[SqlException (0x80131904): Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.]
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) +907
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5968584
   System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) +38
   System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +507
   System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +154
   System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +21
   System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +90
   System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +443
   System.Data.SqlClient.SqlConnection.Open() +96
   System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +75

[HttpException (0x80004005): Unable to connect to SQL Server database.]
   System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +125
   System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) +89
   System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) +29
   System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +386

Here is the webconfig

<?xml version="1.0" encoding="utf-8"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="AuthServices" connectionString="Data Source=localhost\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=authentication;" />
  </connectionStrings>
  <system.web>
    <authentication mode="Forms">
      <forms loginUrl="login.aspx" defaultUrl="main.aspx" />
    </authentication>
    <authorization>
      <allow users="?"/>
      <!--<deny users="?"/>-->
    </authorization>
    <membership defaultProvider="AuthServices" userIsOnlineTimeWindow="30">
      <providers>
        <add
          name="AuthServices"
          type="System.Web.Security.SqlMembershipProvider"
          connectionStringName="AuthServices"
          applicationName="MoldMaint"
          enablePasswordRetrieval="false"
          enablePasswordReset="true"
          requiresQuestionAndAnswer="false"
          requiresUniqueEmail="false"
          passwordFormat="Hashed"
          maxInvalidPasswordAttempts="5"
          passwordAttemptWindow="10" />
      </providers>
    </membership>
    <roleManager
    enabled="true"
    cacheRolesInCookie="true" >
      <providers>
        <add name ="AuthServices"
             type="System.Web.Security.SqlRoleProvider"
             connectionStringName="AuthServices"
             applicationName="MoldMaint"/>
      </providers>
    </roleManager>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.7.2"/>
    <httpRuntime targetFramework="4.7.2"/>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>

</configuration>
vb.net
asked on Stack Overflow May 20, 2020 by McNeal

1 Answer

0

In the role manager section under < system.web >< roleManager > add a default provider inside role manager. I have already declared "AuthServices" in the connection strings section at the top of my original posting.

<roleManager defaultProvider="AuthServices" enabled="true" cacheRolesInCookie="true">
  <providers>
    <add name ="AuthServices"
         type="System.Web.Security.SqlRoleProvider"
         connectionStringName="AuthServices"
         applicationName="MoldMaint"/>
  </providers>
</roleManager>
answered on Stack Overflow May 21, 2020 by McNeal

User contributions licensed under CC BY-SA 3.0