BetterCMS with MVC4 Simple membership provider - asp.net-mvc-4

I've set up BetterCMS in my MVC4 app. and it seems like it's working except I can't figure out how to configure it to use Simple Membership Provider that comes with MVC4 internet app.
http://www.devbridge.com/articles/better-cms-for-developers
please help!. thanks
EDIT: I've created my MVC4 app using Internet Template which comes with Simple Membership Provider already configured and working. I would like to have those members I've "registered" as BetterCMS users.

If you want to use Better CMS, use BetterCms.Module.Users module from NuGet with it's role provider, membership provider and UI for managing users. How to setup users module, you can read in BetterCMS wiki pages on Github
But if you still wish to use Better CMS with Simple Membership Provider, follow steps below. That's what I've done and it works fine for me.
Create an MVC 4 solution and select Internet template
Run the application and create a user
Install BetterCMS by following steps, explained in Better CMS github wiki, section "Project Setup".
Do not forget to remove default routes registration (routes.MapRoute(name: "Default" ....) from RouteConfig class.
Register routes below in the RouteConfig class. After that MVC home page can be reached by URL /home/:
routes.MapRoute("mvc-account-controller", "account/{action}/{id}", new
{
area = string.Empty,
controller = "Account",
action = "Login",
id = UrlParameter.Optional
});
routes.MapRoute("mvc-home-controller", "home/{action}/{id}", new
{
area = string.Empty,
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
Add role provider and membership provider to web.config (solution found here):
<roleManager enabled="true" defaultProvider="simple">
<providers>
<clear/>
<add name="simple" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
<membership defaultProvider="simple">
<providers>
<clear/>
<add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>
</providers>
</membership>
Add LazyInitializer to global.asax as explained here
Remove [InitializeSimpleMembership] attribute from AccountController, because database connection is already initialized. Also, SMP2.Filters.InitializeSimpleMembershipAttribute class can also be deleted.
Create an admin role and assign it for user (it can be done using ASP.NET Configuration or directly in the database). For example, create role with name "Role1".
There are two ways to set up administrator roles for the user (you can read more in the Better CMS Github Wiki, topic "CMS configuration"):
Set your created role as full access role (cms.config, security section's fullAccessRoles attribute set to fullAccessRoles="Role1" )
Add roles mappings in the cms.config's security section:
<customRoles>
<add permission="BcmsEditContent" roles="Role1" />
<add permission="BcmsPublishContent" roles="Role1" />
<add permission="BcmsDeleteContent" roles="Role1" />
<add permission="BcmsAdministration" roles="Role1" />
</customRoles>
Run application. Go to url /account/login and log-in using admininstrator account, which was created in the 2nd step. Then go back to any CMS page, for example, root page (/).
Here you go, you're connected as administrator and CMS sidebar is availabe for web site editing.

Related

Regarding Authorize attribute usage in ASP.Net MVC 4

when we decorate any action with Authorize attribute then how MVC redirect to login form because my login controller name could be different and also view name also could be different. login view also could be stored in different folder instead of shared folder.
so tell me how MVC engine understand that it need to load login form when face Authorize attribute ?
how MVC engine would know where login form template is stored because it location could be different instead of shared folder?
how MVC engine would know what is login controller name if my login controller name is different ?
please discuss 3 points i asked here in details. thanks
The AuthorizeAttribute is a filter, which means that it can execute before the associated controller action. The AuthorizeAttribute performs its main work in the OnAuthorization method. If the user fails authentication, an HttpUnauthorizedResult action result is returned which produced an HTTP 401 status code. In previous versions of ASP.NET MVC the user redirected to the application login page defined in the application's web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
In ASP.NET MVC 5, the redirection process is handled by OWIN middleware components. It redirects unauthenticated requests to a LoginPath value, which
defaults to "/Account/Login":
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType =
DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});

MVC4 Windows Authentication Redirect to Account/Login

I am setting up Windows Authentication in an MVC 4 application using Visual Studio 2013 and using the IIS Express Development Server. However, I get redirected to /Account/Login (as if I were using forms authentication).
I have no reference to WebMatrix in my bin folder (or anywhere) as described here: ASP.NET MVC3 and Windows Auth on IIS keeps redirecting to /Account/Login.
I have added these entries to appSettings in the web.config as suggested by this post:
MVC5 Redirects to Login.aspx when using Windows Authentication
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
Here is what I have done so far:
Added windows authentication to system.web.
<authentication mode="Windows"/>
Added the [Authorize] attribute to my controller. I have also tried using the authorization tag in the web.config instead of the attribute on the controller (deny users="?"). The results are the same.
For the Development Server settings in my project I changed these settings:
Anonymous Authentication = Disabled
Windows Authentication = Enabled
I can find no reference to FormsAuthentication. I can't figure out why it still redirects to a non-existent login page.
When the project was created it may have been done using a template that added Startup.Auth in the App_Start folder in your project. (The default template uses Individual User Accounts if you did not change it to windows authentication as the Authentication method in the create new ASP.Net Project dialog)
Try commenting out these lines if they are present
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
Or if you have not added anything to this file you could remove it completely and the call to it
ConfigureAuth(app);
found in the startup.cs in the root of the project
Now most of the account controller is no good to use if this case so be prepared to clean that up also.
This line is important and correct in the web config
<authentication mode="Windows"/>
these lines are probably not directly related to the issue and can be removed
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
The other development settings are also correct.

Razor create link to route

I've just installed Elmah in my MVC application. It magically added a route in Web.config:
<add key="elmah.mvc.route" value="elmah" />
Which I can access through:
localhost/elmah
How can I create a link to this action in Razor?
#Html.RouteLink("elmah")
or
elmah

How do I use windows authentication with roles with Hot Towel?

I can spin up a standard asp.net mvc 4 intranet project and decorate the controller or methods with things like:
[System.Web.Mvc.Authorize(Roles = "MyApp Users")]
I have tested it and it will work perfectly (since my domain account is a member of the "MyApp Users" in Active Directory)
However my problem/question is how do I get the same type of behavior for a "Hot Towel" application? I try decorating my breeze controller, HotTowel Controller, or any method with the same attribute and I can never authenticate... what gives?
Your help is greatly appreciated.
Finally figured it out. I hope this is of use to others.
First you must set the WindowsProvider as your roleManager like so:
<roleManager defaultProvider="WindowsProvider"
enabled="true"
cacheRolesInCookie="false">
<providers>
<add
name="WindowsProvider"
type="System.Web.Security.WindowsTokenRoleProvider" />
</providers>
</roleManager>
Then you will be able to check the roles for the user [using Roles.IsUserInRole()], and more specifically to this question use the authorize attribute. The only thing is that you will have to include the domain in the authorize attribute, like so:
[System.Web.Mvc.Authorize(Roles = "YourDomain\\MyApp Users")]
And now everything works as you would expect.

How do I reset or change passwords using SimpleMembership in MVC4?

I've been writing a web application using the MVC4 Internet template. I really didn't need anything complicated for user management, so I went with the default SimpleMembershipProvider. I'm initializing membership in App_Start, and I have roles and users set up and working. I am not using SSO or any of the other OAuth features. Now I have a tester that has forgotten his password and after googling all day I realize I have no idea how to just reset his password or change it!
I've read through the documentation and found that the ResetPassword function is not supported if using SimpleMembership. My question is, how do I either:
switch from SimpleMembership to standard membership that uses the SimpleMembership tables and format
reset the user's password to something I specify?
I've found the web.config settings to (theoretically) set the membership provider to use SimpleMembership, but I'm not sure of how to specify the table to use (assuming that's the right way to do it).
web.config section:
<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>
and the current InitializeDatabaseConnection that I (think) I need to have in the web.config:
WebSecurity.InitializeDatabaseConnection("UPEFSSecurity", "Datamart_User", "UserId", "UserName", autoCreateTables: true);
To do this properly you would need to set up an email recovery link. But here's the API calls you would make:
var token = WebSecurity.GeneratePasswordResetToken(username);
// create a link with this token and send email
// link directed to an action with form to capture password
WebSecurity.ResetPassword(token, password);
http://msdn.microsoft.com/en-us/library/webmatrix.webdata.websecurity.resetpassword(v=vs.111).aspx