SimpleMembership, MVC4, AuthorizeAttribute and Roles

11,998

Solution 1

I’ve found the solution (although I’m sure there’s a better way of doing it). Firstly, the database used by SimpleMembership isn’t initialized early enough, so I moved the line:

WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

to the Global.asax file and made sure it got run as early as possible. The line of code can be found in Filters -> InitializeSimpleMembershipAttribute.cs , around line 41

Edit: it seems that this next bit isn’t necessary…

Secondly, the [InitializeSimpleMembership] attribute needs to be added to any class where membership might be an issue—for me that’s all of them, so I added the line:

filters.Add(new InitializeSimpleMembershipAttribute());

to the FilterConfig.cs file in the app_start folder.

These two simple changes seem to have fixed it. I’m sure there are some improvements I could make to the general workings of the SimpleMembership stuff included in MVC4 though—it doesn’t seem very well written (hard coded connection strings etc!), so it could be that these issues can be fixed by making the SimpleMembership stuff well written in the first place!

Solution 2

You shouldn't need to move the first line. I tested by just adding the filter

filters.Add(new InitializeSimpleMembershipAttribute());

Although if you are creating a site that requires you to login you can just have it on that one controller and not have to put it on all of the controllers.

Solution 3

The InitializeSimpleMembershipAttrribute generated by the Internet template for MVC 4 was designed for lazy loading of the SimpleMembership database in the event that the developer is not using forms authentication. If you are using forms authentication it is recommended to remove this filter and initialized it directly. This article describes how to do this.

Solution 4

In MVC4 I was able to add the annotation to my home controller and this error stopped coming up:

[InitializeSimpleMembership]

Also had to bring in the imports at the top as needed:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;

Solution 5

Check InitializeSimpleMembershipAttribute usage, web.config settings for SimpleProviders and may also consider making the InitializeSimpleMembershipAttribute an Authorization Filter specially when using Authorize(Roles="any")

Share:
11,998
Dylan Parry
Author by

Dylan Parry

Web developer living in Gloucester, UK. Currently working with C#, ASP.NET MVC, HTML, CSS, JavaScript.

Updated on July 29, 2022

Comments

  • Dylan Parry
    Dylan Parry over 1 year

    I’m trying to add authorize attributes to some of my MVC4 controllers, and they work fine as long as it’s a plan [Authorize] or [Authorize(Users="myuser")], but the second I add in any sort of role filtering it falls apart, eg. [Authorize(Roles="admin")]. I then start getting errors like:

    Server Error in '/' Application.

    A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance 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.

    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): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
    System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5295167 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +242
    System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +5307115
    System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +145
    System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +920
    System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307
    System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +434
    System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5309659
    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& connection) +5311874
    System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) +143
    System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource
    1 retry) +83 System.Data.SqlClient.SqlConnection.Open() +96
    System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +76

    [HttpException (0x80004005): Unable to connect to SQL Server database.]
    System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +131
    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) +27
    System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +386

    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929

    I’m really not sure what’s going on here. Again, if I remove the roles bit of the authorize attribute, then it works fine (as far as stopping unauthorized users at least) but it’s no good if I have to hard code the admin users into the app!

    Any idea what’s happening here, and how I can make it work properly?

    Thanks,

  • Neil Thompson
    Neil Thompson over 11 years
    +1 Thanks for this. Your solution solved the problem for me. Also found this post for anyone else who hits this issue: stackoverflow.com/questions/12257232/…
  • Randi Ratnayake
    Randi Ratnayake almost 10 years
    Hey @Dylan it did the trick for me and Cheers !! Was struggling this for couple of days now.