WebSecurity.InitializeDatabaseConnection fails with "The Role Manager feature has not been enabled." when called from console program - asp.net-mvc-4

I have a MVC4 application using SimpleMembership to authenticate users.
I want to add users from a console program.
The console program that references a class library that has the method that will do the user creation.
It looks like this:
public class UserBuilder
{
private static readonly SimpleMembershipInitializer _membershipInitializer;
private static readonly bool _isInitialized;
private static readonly object _initializerLock = new object();
static UserBuilder()
{
LazyInitializer.EnsureInitialized(ref _membershipInitializer, ref _isInitialized, ref _initializerLock);
}
public void HandleEvent(UserAdded #event)
{
if (!WebSecurity.UserExists("ReportModels"))
{
WebSecurity.CreateUserAndAccount("ReportModels", "ReportModels");
};
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
}
}
When I start my console application I get System.Configuration.Provider.ProviderException {"The Role Manager feature has not been enabled."} at the line starting with WebSecurity.InitializeDatabaseConnection.
What do I need to do to accomplish this?
I've tried:
adding the nuget package Microsoft ASP.NET Web Pages 2 Web Data to both the console project and the class library project.
the answers listed in this post: SimpleMembershipProvider not working.
verified the connection string.
verified that the tables are in place in the database.
verified that creating users and authenticating them from the MVC4 project works.

Finally solved it thanks to information found in this blog post: http://insomniacgeek.com/to-call-this-method-the-membership-provider-property-must-be-an-instance-of-extendedmembershipprovider/ and some googling.
In essence I needed to add this to my app.config file:
<system.web>
<profile defaultProvider="SimpleProfileProvider">
<providers>
<add name="SimpleProfileProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"
connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
<roleManager defaultProvider="SimpleRoleProvider" enabled="true">
<providers>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
</system.web>
Please note the enabled="true" on the roleManager element. Without that the same exception will be thrown.

Related

Serilog : creating Multiple log files when calling a wcf service

I have serilog parameters described in web.config as below:
<appSettings>
<add key="serilog:minimum-level" value="Debug" />
<add key="serilog:using:RollingFile" value="Serilog.Sinks.RollingFile" />
<add key="serilog:write-to:File.rollingInterval" value="Day"/>
<add key="serilog:write-to:RollingFile.pathFormat" value="c:\temp\log.txt" />
</appSettings>
In my wcf service, code is as below
public class CalculateService : ICalculateService
{
private Logger _logger;
public CalculateService()
{
_logger = new LoggerConfiguration()
.ReadFrom.AppSettings()
.CreateLogger();
_logger.Debug("calling constructor");
}
}
When I'm calling this service from the Console application, a separate log file is created each time. I want to initialize log only once and want to create a new log file each day.

Is Active Directory authentication used?

I've inherited MVC4 application. It looks like Windows Authentication is used, but I also was told that "Active Directory Authentication" is used for some permissions. I do not see anything in web.config about Active Directory.
In web.config:
<authentication mode="Windows" />
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=21bf1234ad634e53" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
In Controller:
[Authorize(Roles = #"ABCD\EFG"), HandleError(ExceptionType = typeof(UnauthorizedAccessException), View = "UnauthorizedUser", Order = 1)]
public class HomeController : Controller
{ .............
}
public ActionResult MyAction()
{
if (!User.IsInRole(#"ABCD\EFG"))
{
// some code
}
//.............
}
Is "Active Directory Authentication" used in this application ?
Thank you
The windows authentication will indeed integrate with Active Directory as long as the application server is on the domain your users are registered in.
The below line in your config file enables such functionality.
<authentication mode="Windows" />
This post might help you get further:
Configure ASP.NET MVC for authentication against AD

Move simple membership profider functionality to class library project

I'm trying to move my DbSet's to a class library project that is going to be used for database operations.
I've been following this tutorial to a Code First / SimpleMembershipProfider project. I've already got the database filled with new tables etc, via the class lib project.
But i am missing the webpages_ tables you can see on this image.
This is my datacontext class:
public class DataContext : DbContext
{
public DataContext() : base("DefaultConnection")
{
}
public DbSet<Orders> Orders { get; set; }
public DbSet<Appointment> Appointment { get; set; }
public DbSet<UserProfile> UserProfile { get; set; }
}
And for every DbSet i created a cs file. I copied the connectionString from the web.config and placed it in the app.config in the class lib project. This is how the app.config file looks like:
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=aspnet-CodeFirst-test;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear />
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
</system.web>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
I'm not sure what to do with the Filters folder (which has the class InitializeSimpleMembershipAttribute) in my webproject.
Can someone tell me how to get the webpages_ created in the database? And how to move websecurity etc to the class lib project?
Thanks in advance!
If you trying to take control of Asp.net Simple Membership Table and or Including Asp.net Simple Membership Tables as Part of Your Entity Framework Model your Project Entity framework, there is a number of steps you need to take. I would explain them step by step but it would take too long so i will just provide you with references.
Including Asp.net Simple Membership Tables as Part of Your Entity Framework Model
Seed Users and Roles with MVC 4, SimpleMembershipProvider, SimpleRoleProvider, Entity Framework 5 CodeFirst, and Custom User Properties
Building Applications with ASP.NET MVC 4. You can use trial version on pluralsight
If you have any specific questions, i would be happy to answer them.

How can I check a user is in a role in ASP MVC4 Simple Membership?

I am familiar with:
WebSecurity.IsCurrentUserInRole("Admin")
But this does not seem to work any more. Is there another way I can check in my controller if a user is in a role when I am using SimpleMembership?
You can use
if (User.IsInRole("Admin"))
{
}
And webConfig
<system.web>
<roleManager enabled="true" />
....
After Comment
you can use something like this:
foreach (string rolesForUser in Roles.GetRolesForUser(User.Identity.Name))
{
if (User.IsInRole(rolesForUser))
{
}
}
I think there is an elegant way to do this...
You'll need to have a RoleProvider setup as well
Since you are using SimpleMembership, you probably should use SimpleRoleProvider as well.
You can either create the roles programatically by calling Roles.CreateRole or use the RoleManager web interface.
<roleManager enabled="true" defaultProvider="simple">
<providers>
<clear/>
<add name="simple" type="WebMatrix.WebData.SimpleRoleProvider,
WebMatrix.WebData"/>
</providers>
</roleManager>

Getting an error implementing Roles in MVC 4

I am trying to register a user to a role but i am getting the following error:
No user found was found that has the name "MyName"
I have created an MVC 4 Application using the default template.
I have created a custom membership provider and implemented the CreateUser method as follow
public User CreateUser(User i_userToCreate)
{
using (var _db = new Repository())
{
User _user = _db.CreateUser(i_userToCreate);
MembershipUser _membershipUser = new MembershipUser(providerName: "ATWMembershipProvider",
name: _user.UserName,
providerUserKey: null,
email: _user.Email,
passwordQuestion: "",
comment: "",
isApproved: true,
isLockedOut: false,
creationDate: DateTime.UtcNow,
lastLoginDate: DateTime.UtcNow,
lastActivityDate: DateTime.UtcNow,
lastPasswordChangedDate: DateTime.UtcNow,
lastLockoutDate: DateTime.UtcNow);
return _user;
}
This is how i configured my web.config
<appSettings>
<add key="enableSimpleMembership" value="false"/>
<add key="autoFormsAuthentication" value="false"/>
</appSettings>
<system.web>
<membership defaultProvider="ATWMembershipProvider">
<providers>
<clear/>
<add name="ATWMembershipProvider" type="AroundTheWorld.Infrastructure.ATWMembershipProvider"
enablePasswordRetrieval="false"
ConnetionStringName="Context"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
equiresUniqueEmail="false"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10" applicationName="myApplication" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">
<providers>
<remove name="AspNetSqlRoleProvider" />
<add name="AspNetSqlRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<!-- note: WebMatrix registers SimpleRoleProvider with name
'AspNetSqlRoleProvider'. I don't know why but i kept it. -->
</providers>
</roleManager>
Now the authenticate method is as follow:
var MembershipProvider = new ATWMembershipProvider();
User authentictedUser = MembershipProvider.CreateUser(_userToCreate);
FormsAuthentication.SetAuthCookie(authentictedUser.UserName, true);
System.Web.Security.Roles.AddUserToRole(authentictedUser.UserName, authentictedUser.Role.Name);
Session.Add("UserID", authentictedUser.ID);
Session.Add("UserName", authentictedUser.UserName);
I have already checked the following:
My User as all necessary information
I have registered two roles in App_start "user" , "admin"
but i still getting an error that No user found was found that has the name "MyName"
In asp web form that wasn't necessary in order to secure a folder based on a role
All i am trying to do is to secure an action inside a controller to a specific "Role"
[Authorize(Roles = "admin")]
public ActionResult GetAllLocations()
{
using (var _db = new Repository())
{
return View(_db.GetLocations());
}
}
I have fixed the problem...
The problem was because I implemented only a custom membership provider without a role provider.
I have followed this blog.
Basically I have created a class MyOwnRoleProvider which inherits from RoleProvider
and:
Implemented the method called GetRolesForUser
Implemented the method called GetUsersInRole
finally I modified my web.config to
<roleManager defaultProvider="ATWRoleProvider" enabled="true" cacheRolesInCookie="true">
<providers>
<clear />
<add name="ATWRoleProvider" type="AroundTheWorld.Infrastructure.ATWRoleProvider, AroundTheWorld" connectionStringName="Context" />
</providers>
</roleManager>
after it I was able to use the following
[Authorize(Roles="admin")]
public ActionResult GetAllLocations()
{
using (var _db = new Repository())
{
return View(_db.GetLocations());
}
}
AND
#if (User.IsInRole("user"))
I hope it will be helpful for someone...