SecurityGuard - NuGet Package for the ASP.NET Membership system
SecurityGuard is a complete ASP.NET MVC 3 and MVC 4 application installable via NuGet. If you need a complete way to manage your ASP.NET Membership system for your MVC application, this is the NuGet package to use.
Don't forget to watch the screencast on how to quickly install it and use it.
If you don't know what NuGet is, it's a free online resource that contains components that can easily be installed into your applications for various needs. Go to NuGet.org for more information.
AN IMPORTANT NOTE: SecurityGuard is built on the .Net 4.0 framework so it's only available with ASP.NET MVC 3 or 4!
Pre-requisites:
- .Net 4.0 Framework
- ASP.NET MVC 3 or 4 host application
- ASP.NET Membership is installed based on the System.Web.Providers namespace (not the SimpleMembershipProvider yet)
==== Update for Version 1.0.10 ====
- FIXED: The BeginForm was blank on the EnterSecretAnswer.aspx view, when it should have been pointing to SGAccount/ForgotPassword. Thanks to Paul Randall for catching this.
==== Update for Version 1.0.9 ====
- FIXED: ReturnUrl was null in Login Action. Special thanks to Behrooz for pointing this out.
==== Update for Version 1.0.8 ====
- FIXED: ForgotPassword feature when RequiresQuestionAndAnswer equals true. It no longer returns an error.
==== Update for Version 1.0.8 ====
- FIXED: updated the web.config.transform - changed the forms element/loginUrl to point to the new ~/SGAccount/Login, not LogOn. This is to match the change made in the SGAccountController.
==== Update for Version 1.0.6 ====
- FIXED: broken mailer in 1.0.5. Replaced mailer function to use MvcMailer for the ForgotPassword process.
==== Update for Version 1.0.5 ====
- Changed the name LogOn to Login to match the default method name.
- Added ValidateAntiForgeryToken attributes to ChangePassword, ForgotPassword, Login and LogOff action methods.
- Changed the AcceptVerbs on the LogOff action to accept both Get and Post methods.
- Added the Html.AntiForgeryToken() extension to the ChangePassword, ForgotPassword, Login and Register views.
- Updated the Compare attributes on the ChangePassword and Register ViewModels to be fully qualified to the System.Web.Mvc namespace.
==== Update for ASP.NET MVC 4 Beta - 5/25/2012 ====
A new NuGet package is now available for MVC 4 Beta!In your Package Manager Console, just enter:
PM> install-package SecurityGuard.MVC4
Here is all that was done to make this work.

So to be clear, you do not need to do anything but install the MVC 4 version in order to make it work.
Thanks to Leniel Macaferi for pointing this out. https://github.com/leniel
If you have any problems, create an issue in github. https://github.com/kahanu/Security-Guard
==== End Update ====
What SecurityGuard does not do
SecurityGuard does NOT install the required ASP.NET Membership system. You need to have that installed prior to installing SecurityGuard. SecurityGuard is the UI components for you to manage your membership system. There are many ways you can install the ASP.NET Membership system, but the easiest way is with my other NuGet package called MvcInstaller. Check it out at NuGet.org, and take a look at my other article as part of this series on what the MvcInstaller NuGet package is and how it works.After the ASP.NET Membership system is installed, simply install the NuGet package for SecurityGuard and it's 99.9% done. You will have to do a few things to tailor it to your application and for configuration, but they are mostly minor view modifications.
INSTALLATION
To install and configure SecurityGuard correctly will depend on what version of Visual Studio you are using. At the moment it is intended to be used with VS 2010 and VS 2012. It has not been thoroughly tested with VS 2008.I will cover both installation versions so it's as painless as possible to get up and running.
Install SecurityGuard in an ASP.NET MVC 4 Application in Visual Studio 2010
This is the easiest of the two IDE's to install and configure SecurityGuard.Step-by-step Installation and Configuration
- ConnectionString - set your connection string to point to your database
- Membership Sections - make sure your Membership sections are included in the web.config file and that they are using the System.Web.Providers namespace. (These first two steps are done automatically for you with MvcInstaller)
- Install SecurityGuard - in Visual Studio, open your Package Manager and enter: install-package securityguard.mvc4, and press Enter. This will install all the necessary files and configuration for the application.
- Remove Forms element - in the web.config, in the system.web/authentication element, there are now two "forms" elements. You need to delete the element that has
"~/Account/LogOn"for the loginUrl value. The leaves the one with "~/SGAccount/Login" as the loginUrl value. - Remove SGAccount views - in the Views folder of the MVC application, open the SGAccount folder. You will see all the views needed in both WebForms (ASPX) and Razor (cshtml) files. You need to delete the version of the files that you are not using.
- Configure SMTP element - this is necessary in order to use the ForgotPassword feature which will email the newly created password to the user.
There is more details on these steps below.
You can use the Package Manager Console or the GUI. I'll demonstrate how to install using the console.

Step 3
Now you will see the console where you enter the following:PM> install-package SecurityGuard.Mvc4
After you hit Enter, you'll notice many files being copied into your application. These are all the files necessary to run the application. Controllers and other C# classes are also being added with your applications namespace so they are assured to work.
Also, a new Area is created called SecurityGuard. This contains all the controllers, models and views for the application. CSS and images have also been included in the Content folder.

Step 4
The next change is in the web.config file. It places a duplicate forms
authentication node in the file and the default node needs to be
removed.
This is the authentication section after SecurityGuard has been installed.
1.<authentication mode="Forms">2. <forms loginUrl="~/Account/LogOn" timeout="2880" />3. <forms loginUrl="~/SGAccount/LogOn" timeout="2880" />4.</authentication>Now you need to remove the forms node on line 2 so it leaves the one you want which points to the SGAccount controller.
Step 5
In the SGAccount folder in the Views folder, you'll see a large set of views for the operations needed.

SecurityGuard can only work with a single set of views, so you need to delete the set of views that do not match the view type you are working with.
For example, I like to work with the Razor views, so I'm going to select all the WebForms views to delete them.

Now I simply click the Delete button and all those views go away.

Now my application will not throw any exceptions. If you fail to do this step you will see an exception since the view engine is looking for a particular type of MasterPage. (See the Troubleshooting section at the bottom of this article for more information.)
Step 6
Next, the smtp section should be updated
with your SMTP server information. This is used for the Forgot
Password component. It will email the new password to the user.
1.<system.net>2. <mailSettings>3. <smtp deliveryMethod="Network" from="[your support email address]">4. <network enableSsl="true" host="[smtp server name]" userName="[email address]" password="[email password]" port="587" />5. </smtp>6. </mailSettings>7.</system.net>One quick note about this section, if you set the enableSsl="true", then it's up to you to make sure you have a working port for your secure SMTP server. If you don't, the operation will timeout and fail.
Install SecurityGuard in an ASP.NET MVC 4 Application in Visual Studio 2012
The first thing you need to be aware of is that SecurityGuard CANNOT be used with ASP.NET MVC 4.5 applications that are already configured to use the SimpleMembershipProvider. This is because SecurityGuard has not been built around the SimpleMembershipProvider yet, and it has a completely different schema and framework.SecurityGuard CAN be used with applications created in VS 2012 from scratch or applications that have not yet incorporated any Membership system.
SecurityGuard uses the System.Web.Providers namespace for the membership system. I think this new provider rock! If you don't care if you aren't going to use the SimpleMembershipProvider, then you can safely install and use SecurityGuard in VS2012 and .Net 4.5.
The steps to install SecurityGuard are pretty much the same as for the VS2010 installation, but there are a couple things you need to do since there are differences.
No Providers in Web.config
If you are creating a brand new MVC 4 application in VS2012, you'll notice something after the application is finished being created in Visual Studio. The web.config file has no membership providers sections. This is because it's using the new SimpleMembershipProvider and those providers are included in the machine.config file.
So in order to use SecurityGuard in this application, which uses the System.Web.Providers namespace, that assembly needs to be included in the application references AND all the membership sections need to be added to the web.config.To do this there are a couple ways of doing this, and both are pretty easy:
- Manually
- Use MvcInstaller
The reason to use the Manual method to include the assembly and configuration sections is mostly because you already have a database created with a full working schema, so all you need are these sections and the updated connectionStrings configuration in order to connect your application to your database.
The easy way to do this is via NuGet. In Package Manager, enter:
PM> install-package system.web.providers
... and hit Enter. It will install the assembly reference as well as place all the membership sections in the web.config file. All you need to do is update the connectionStrings key to point to your database and then update the membership sections for the connectionStringName. If you create an application name, then you'll need to update that value in those sections also.
The reason to use the MvcInstaller method is if you are creating the application from scratch but you have a database schema in SQL Server. MvcInstaller will read the schema and update your web.config for you. It will also add the necessary reference to the System.Web.Providers assembly. For more information on MvcInstaller I urge you to read the companion article and watch the video.
Common Configuration
NOTE: the appSettings key, SecurityGuardEmailFrom is deprecated. It's not really something you have to worry about. It was used to set the From value in the outgoing email when the ForgotPassword command is executed. Now the value comes from the smtp element in the web.config.
The rest of the information below are common configuration changes that you can make to your application, but they aren't required. It's entirely up to you how you make this changes.LoginPartial Updates
Now you'll need to make a few little changes. The first you'll make is to the _LoginPartial.cshtml view. You will change the controller names to point to the new SecurityGuard Account controller.01.@if (Request.IsAuthenticated) {02. <text>03. Hello, @Html.ActionLink(User.Identity.Name, "Manage", "SGAccount", routeValues: null, htmlAttributes: new { @class = "username", title = "Manage" })!04. @using (Html.BeginForm("LogOff", "SGAccount", FormMethod.Post, new { id = "logoutForm" })) {05. @Html.AntiForgeryToken()06. <a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>07. }08. </text>09.} else {10. <ul>11. <li>@Html.ActionLink("Register", "Register", "SGAccount", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>12. <li>@Html.ActionLink("Log in", "Login", "SGAccount", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>13. </ul>14.}NOTE: this has been updated for the new version of SecurityGuard v.1.0.5 to include the @Html.AntiForgeryToken() extension method, which will match the VS 2012 procedures.
You can see on lines 3, 4, 11, and 12 that I've changed the default "Account" controller name to "SGAccount". Now I want to make a change to my global menu navigation for the application. This is different for every application, so there's no way for me to build something into the NuGet package to do this for you.
01.<nav>02. <ul id="menu">03. <li>@Html.ActionLink("Home", "Index", "Home")</li>04. <li>@Html.ActionLink("About", "About", "Home")</li>05. @if (User.Identity.IsAuthenticated)06. {07. <li>@Html.ActionLink("Change Password", "ChangePassword", "SGAccount")</li>08. }09. @if (User.IsInRole("SecurityGuard"))10. {11. <li>@Html.ActionLink("Security Guard", "Index", "Dashboard", new { area = "SecurityGuard" }, null)</li>12. } 13. </ul>14.</nav>You can see I've added a "Change Password" link and a link to the "Security Guard" area. But you'll also notice that I've wrapped them in conditional statements. For the Change Password link, the user needs to be logged on to see this. For the Security Guard link the user needs to be logged on and in the "SecurityGuard" role.
Now that that's done, you are ready to use the application.
Ready To Go
Now you can run your application and you should see your site come up as usual. For the rest of this we will assume that I've already installed and configured the ASP.NET Membership system on this server, or local development machine and I've created a user and assigned it to the SecurityGuard role.To log in as the SecurityGuard role, you just need to log on with those credentials that are assigned to that role. The application will check the credentials in order to give you access to the SecurityGuard Area. A user who logs in that has either no association with a Role or has a less privileged Role, will not gain access to the SecurityGuard Area.
When I log into the site, I should see something like this.

When I click on the "Security Guard" link, I'll be taken to the SecurityGuard MVC Area and I'll see this.

It's a simple, clean web-interface that allows you to easily manage the membership system. Let's go through the application.
Roles
When I click on the "Manage Roles" link, I'll see this page.
This allows you to enter and delete roles on the left side, and see the users in a particular role on the right side.
Selecting a role to see what users are in that role, looks like this.

You can click on the user name and be taken to the details for that user.
Validation is built in. You can see it working if you try to Add a role without a name entered.

When you enter a role, you will see a success message and it will be added to the Roles list and the Users In Roles list via jQuery Ajax.

Deleting roles is just as easy, but the ASP.NET Membership system has a "check" for users granted to the deleted role. By default, if you try to delete a role that contains users, then it will complain and not let you do it. But it you really want to do it, you can tell the system to go ahead and delete the role and any associated users by checking the box "Delete role if it has users?". This tells the system to go ahead and delete everything.
Manage Users
Managing users is also just as simple. To get back to the Dashboard home page, I just need to click the "Dashboard" link in the top breadcrumb. Then I click on the "Manage Users" link and I'll see this page.
There's a lot happening on this page. First, the drop down list has three selections, "View All", "UserName", and "Email". These are the different filtering methods you can use to manage users.
- View All - this setting doesn't allow you to enter a value in the search box since you are viewing all users.
- UserName - this filter setting allows you to enter a value into the "Starts with:" field. Enter any set of characters that the username would start with.
- Email - this filter setting allows you to enter a value into the "Starts with:" field. Enter any set of characters that the email would start with.
The radio button is a quick way to jump to the "Grant Roles to User" view. Simply select a radio button for a user and the "Grant Roles To User" link above becomes enabled and if you click on it, you will be taken to that view for the selected user. It looks like this.

This shows the roles that are already granted to the user and what roles are still available to be granted. To Grant or Revoke a role, simply select the role in the list box and click the appropriate button. The command is executed instantly via Ajax.

User Details
Viewing user details is one of the views you will most likely visit often. It's a clean interface and allows you to do manage certain details in a friendly Ajaxified manner.
The Update button in the lower right only updates the values from the email and comment fields. You can easily Approve or Deny a user by clicking the link next to that value. It will execute the command via Ajax. The same goes for the Locked out value. If the user is locked out, a link will appear that allows you to quickly unlock them.
Also, at the bottom of the page, you can click the "Edit" link next to "Roles for [user name]", and you'll go back to the "Grant Roles to User" view.
Create User
It's just as easy to create a new user. From the main Dashboard view, click the "Create User" link.
There are a few nice things built into this view. Much of this view displays attributes from the web.config/membership section. It shows the number of characters that the username should be, and it will also display how many characters non-Alphanumeric characters should be if they are not zero.
It will also dynamically display the Secret Question and Answer fields if the web.config has that set to True.
This view also has Ajax-validation built in. If you try to submit it without any values in the fields, it will display messages nicely.

Once the user is created, you can instantly view it's details.
Conclusion
That's SecurityGuard. I very nice User Interface for managing your ASP.NET Membership database. It's easy to install and just as easy to configure.Do forget to view my other article in this series on the MvcInstaller NuGet package. This package installs the ASP.NET Membership system for you based on your specifications.
Updates
- November 11, 2011 - Version 1.0.51.575 - made modifications to several files so SecurityGuard will work with or without T4MVC. T4MVC threw some namespace collision exceptions on the RegisterViewModel being using inside the Areas.SecurityGuard.Models folder and when calling SGAccountController and the register view.
Troubleshooting Issues
- The required anti-forgery form field "__RequestVerificationToken" is not present. - in version 1.0.5 I've updated the SGAccountController to verify the AntiForgeryTokens for Login, Logoff, ChangePassword and some others, so you'll need to include the @HTML.AntiForgeryToken() extension method in your HTML inside a form for LogOff and others. See the LoginPartial Updates chapter above for information.
- The file "/Views/Shared/Site.Master" does not exist. - if you see this error it simply means that you are most likely using the Razor views and you forgot to delete the WebForms (ASPX) views in the SGAccount folder in the Views folder. Just delete those files and the application will work.

- The element <forms> may only appear once in this section. - the problem is clearly shown in the exception. It means that you forgot to remove the old forms element that points to "~/Account/Login". Just delete that element and the application will work.

- To call this method, the "Membership.Provider" property must be an instance of "ExtendedMembershipProvider". - If you get this error it's most likely because you clicked on the Manage link in a VS 2012 MVC application. This link points to the original AccountController and not the SGAccountController. This Manage command is specific to the default MVC template that comes with VS2012 and has nothing to do with SecurityGuard. In other words, ignore it. The primary command that it contains that you would want is the ChangePassword command. SecurityGuard has that command already, so simply remove all references to any default commands and just use the SecurityGuard commands.
- The "Manage" view or controller action doesn't exist in SGAccountController - this is by design. As I mention in the previous bullet point, this "Manage" command is built into the default MVC template in Visual Studio 2012. It has nothing to do with SecurityGuard. The Manage view contains some commands that work with the External login options this template gives you, such as Facebook, Google, etc. It provides a way of setting your local account to the external account, changing your password, etc. I have not yet implemented any means of synching up to external logins, so there is no need for the Manage command in existing version as of 1.0.9. So for now, just ignore this and use the commands in SecurityGuard.


Hi kahanu,
This is an excellent addition to the MVC stack,its safe my time as i have been contemplating of developing a user management system similar to what you have done,great work keep it up.
I run into one issue after following your instruction on how to install and use Security Guard NuGet package,the issue is as follows:
1. Error 1 The type or namespace name 'Pagination' does not exist in the namespace 'SecurityGuard.Core' (are you missing an assembly reference?)
2. Error 2 The type or namespace name 'PaginatedList' could not be found (are you missing a using directive or an assembly reference?)
I know this a trivial issue,but please could you verify
@ola, oops! Sorry about that. I pushed the latest SecurityGuard.dll that has the necessary components. I haven't been able to test it since I'm out of town, but it should work. Please let me know if this version works. I want to stay on top of this. Thanks for the catch.
King Wilder
I love the work you have done! So far everything is working and working well!
I had one error while testing. I am using gmail for my email server and it requires SSL. The package you are using for emailing doesn't take the port for SSL. I had to change your code to use a custom function for sending emails. Let me know if you want the code I used.
Thanks again for the great work
@boltojam, I'm glad you like it. I actually have not tested it against an SSL server, but have you tried adding the port to the web.config/system.net/mailSettings/smtp/network element? You should just be able to point to your secure mail server and include the SSL port there and it should all work without any code modification.
I'll test it out when I have a moment. What code did you modify?
Let me know if this works.
bob, yes I've noticed that. It seems to update the list on the first addition, but after that, it doesn't. It's a bug, not a huge one, but a bug. I will fix that at some point. I'm in the middle of a large project right now and can't but it is on my list of TODO's.
Thanks.
Hello Kahanu,
I have successufully install and tested your application ... But there is a bug with the "Forgot Password ?" features ... SGAccountController.cs line 238 :
if (membershipService.RequiresQuestionAndAnswer) { newPassword = user.ResetPassword(model.PasswordAnswer); }Value cannot be null.
Here is my web.config setup, did it make something wrong ? :
Hugo, I'll check it out when I have a moment. Thanks for the report. Did you get this error even if you entered your password?
Thanks,
King Wilder
I just fill the forgot password form with my email and click the reset password button ... It's the only field on this form ...
Thanks you !
Hugo
Hugo, ok, I'll check it when I have a moment.
Thanks,
King Wilder
Hi,
Any updates on the bug where the roles list gets updated on the first addition, but after that, it doesn't.
Thanks!!
vabgujral,
Sorry, no I haven't had time. I'm building my 4th web application for a client just this year and haven't had a free moment. I will try to take a look at it this weekend.
Thanks,
King Wilder
Hugo, I could not reproduce the error you are getting with the password reset issue. I assume you have the SMTP settings in the web.config entered correctly. Let me know if it's still occuring.
Thanks,
King Wilder
Hugo, it looks like you may have setup your ASP.NET Membership system initially without requiring a Security Question and Answer, and then changed it afterward. Is that possible? If so, then the security question and answer columns may be empty for the password you are trying to reset. If that's the case then you need to add them.
At this point the easiest way to do that is to add them manually using the ASP.NET Configuration in your web app project. This allows you to manage your users and roles. Try that and see if it works.
Thanks,
King Wilder
Hi King Wilder,
Did you got an opportunity to work on the bug where roles list not gets updated from second time.
Thanks!!
vabgujral, yes I had time to update it this weekend.
It was a simple change that you really don't need a complete update for. You can make the change yourself in the code if you want.
In Area --> SecurityGuard --> Views --> Role -- Index.cshtml...
... in the $("#add-role") jQuery function, just add a new "cache: false" property to the $.ajax call.
$("#add-role").click(function () {
var roleName = $("#RoleName").val();
if (roleName == "") {
ShowMessage("Please enter a role name.");
return;
}
$.ajax({
url: '@Url.Action("CreateRole", "Role")',
dataType: 'json',
type: 'POST',
cache: false, <-- new property
data: { roleName: roleName },
success: OnCreateRoleSuccess,
error: OnCreateRoleError
});
});
I hope this helps.
Sheven, for the Layout page, you are looking in /Areas/SecurityGuard/Views/Shared/ and not the Root/Views/Shared/ folder, correct?
If it still isn't there, you can try to uninstall SecurityGuard and then re-install it.
Regarding the SecurityGuard menu item, you have to create that manually. You should watch my screencast. Every developer creates navigation differently so there is no way for me to anticipate that and create the menu for you.
I hope that helps.
King Wilder
Sheven,
Sorry you are having these problems.
SecurityGuard is simply a way to manage your ASP.NET Membership system for your MVC application. It does NOT install and configure the ASP.NET Membership system. For that you can use my other NuGet package called, MvcInstaller.MVC3.
With MvcInstaller.MVC3, it will install your database schema and the ASP.NET Membership system for you and have it configured based on the settings you create in the Installer.Config file.
You should watch the videos again for both MvcInstaller and SecurityGuard and see if you've missed something. I've made them so they can actually work together. I use them in every MVC application I build and they work without issues.
I hope this helps. Let me know if you still have more issue.
King Wilder
Hi kahanu,
I have followed all the steps as mentioned above. I am able to get security guard and change password tabs in my screen. After log on as admin if i click on security tab it is again asking to log on and still in the top it is showing welcome admin, but it is not happening for change password. Can you please help.
Thanks,
Vinay
Vinay,
I'm not sure what the problem is here, but it sounds like it might be an issue with either an Authorize attribute on a controller that has a Role that is not authorized, or it could be that your link is pointing to the wrong controller.
You should probably double check your controllers and see what Roles you have set in your Authorize attribute to see if that's the issue.
The reason you can get to Change Password, is because it doesn't have any Role restrictions on it.
I hope that helps.
King Wilder
Dear King Wilder,
I'm really happy right now because I found this awesome NuGet package... I'll help you spreading the word about it. I started answering this question at StackOverflow: http://stackoverflow.com/q/4974703/114029
I'm trying SecurityGuard in a new app built with ASP.NET MVC 4. I had to make minor changes to make it work. Until now I had to
1 - Add a new dependent assembly binding redirect in the MVC 4 app Web.config as per this answer at StackOverflow http://stackoverflow.com/a/10556822/114029:
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages.Razor"
publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
</dependentAssembly>
2 - Changed @Html.TextBox("searchterm", Model.SearchTerm, null) to @Html.TextBox("searchterm", Model.SearchTerm, null, null) inside \Areas\SecurityGuard\Views\Membership\Index.cshtml
Let's see what else I'll have to change. Haven't explored much yet but read this Story (I confess I'm excited with it)...
So, keep evolving this great addition to any ASP.NET MVC app... :D
All the best,
Leniel
Leniel, thanks for finding a temporary fix until I get time to make a new version of SecurityGuard for MVC 4.
As far as you can see, there are no other MVC 4 C# related changes that are necessary?
When I have a moment, hopefully this weekend, I'll look at the MVC 4 bits and work on creating a new version.
Thanks again and I'm glad you like it.
Hi King Wilder,
I have followed all the steps as mentioned above. I am able to get security guard and change password tabs in my screen which works and looks very good.
In my project properties --> Signing tab we have checked "Sign the assembly" checkbox which is a requirement for our project.
When i build the project i am getting the below 2 errors.
Error 1 Assembly generation failed -- Referenced assembly 'MVCCentral.Framework' does not have a strong name.
Error 2 Assembly generation failed -- Referenced assembly 'SecurityGuard' does not have a strong name.
I understood that since these two assemblies does not contain strong name and are added in reference I am getting these errors.
Is it possible for you to provide dlls that have strong name or is it possible for you to shared these 2 dlls code.
Is there any other way through which we can resolve this issue.
Thanks,
Vinay
@Vinay, is there some reason you have to sign your application?
If you want the MVCCentral.Framework code, you can download it at http://www.kingwilder.com/downloads/MVCCentral.Framework.zip.
You can download SecurityGuard at github. https://github.com/kahanu/Security-Guard
I never considered strong-naming these assemblies. Good luck.
Great job!
Minor bug on the Manage Users screen. The url link to associate roles gets appended again and again due to this section:
var href = anchor.attr("href");
// Concatenate the existing href value with the username
var newHref = href + "/" + userName;
I replaced as follows:
Declared this at the top level:
var basehref;
Added to sginit:
basehref = anchor.attr("href");
Replaced problem lines with:
var newHref = basehref + "/" + userName;
Cheers,Jason
@Jsobell, thanks for the information on the fix. You are the second person to find this. I'll be fixing it this weekend.
Thanks again.
Thanks :) Awesome work
for the person who ask about the resetpassword. you need to enable false to true for requiresquestionandaswer in web.config. then you need to modify SGAccountController.cs to handle PasswordAnswer. if you are using it without the try catch you will get error if user answer is wrong you need to redirect.
if (membershipService.RequiresQuestionAndAnswer)
{
try
{
newPassword = user.ResetPassword(model.PasswordAnswer);
}
catch
{
return RedirectToAction("ForgotPasswordFailed");
}
}
Hey, great software module... :)
BUT I get an error if I press the INSTALL button.
This text is viewed:
Bezeichner (beginnend mit 'X ...........g..............���................................0....../.........~.~.�.�.�.�.�.�.�.�.�.�.�.�.�.�.�.�.�.�.') ist zu lang. Die maximal zulässige Länge beträgt 128. Falsche Syntax in der Nähe von 'ӚC'. '.........0..<' ist ein ungültiger Name, da er ein NULL-Zeichen oder ein ungültiges Unicode-Zeichen enthält. Bezeichner (beginnend mit '.........�?......�?).........�?......�?,.........�?......�?..........�?......�?1.........�?..�?..�?3.........�') ist zu lang. Die maximal zulässige Länge beträgt 128. Bezeichner (beginnend mit '5�A..�@........................................................................................................................') ist zu lang. Die maximal zulässige Länge beträgt 128. '.f.i.l.e.g.u.i.d.6............f.i.l.e.i.d.6............f.i.l.e.i.d.6...........' ist ein ungültiger Name, da er ein NULL-Zeichen oder ein
When clicking "Security Guard" I get the error below. I thought i followed the video to the letter, but I obviously did something wrong. Can you point me in a direction?
The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Dashboard/Index.aspx
~/Views/Dashboard/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Dashboard/Index.cshtml
~/Views/Dashboard/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml
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.InvalidOperationException: The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Dashboard/Index.aspx
~/Views/Dashboard/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Dashboard/Index.cshtml
~/Views/Dashboard/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml
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:
[InvalidOperationException: The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Dashboard/Index.aspx
~/Views/Dashboard/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Dashboard/Index.cshtml
~/Views/Dashboard/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml]
System.Web.Mvc.ViewResult.FindView(ControllerContext context) +285778
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +121
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +242
System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +21
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +324
System.Web.Mvc.Controller.ExecuteCore() +106
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +91
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +34
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +19
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +48
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9615056
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
@Jamiu - do you mean you need to create different permissions for different users? If so, then you can simply create new Roles and then assign users to those roles. Then apply those roles to either the Controllers and/or Controller actions so only those users in those roles are allowed to access those resources. Does this make sense?
The other option is to create your own Membership Provider based on the default ASP.NET Membership providers. There are many MSDN articles on how to do this. http://www.asp.net/web-forms/videos/how-do-i/how-do-i-create-a-custom-membership-provider
You have probably observed that MVC4 uses EF for membership, with a different db structure.
Any plans to update SecurityGuard to work with the new scheme?
@lwh, yes I have seen that the MVC 4 framework uses EF for Membership with the new DB schema. I do plan on updating SecurityGuard with the new providers but I'm trying to find out from the ASP.NET team if there is a similar method of creating the database schema as with the System.Web.Security namespace.
I will make an announcement when I'm able to use that.
Thanks.
Getting the same error as a previous user. Didn't see a response here. What is the fix? I see that the Dashboard view files are missing, although the NuGet install seems to have worked fine.
Server Error in '/' Application.The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Dashboard/Index.aspx
~/Views/Dashboard/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Dashboard/Index.cshtml
~/Views/Dashboard/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml
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.InvalidOperationException: The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Dashboard/Index.aspx
~/Views/Dashboard/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Dashboard/Index.cshtml
~/Views/Dashboard/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml
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:
[InvalidOperationException: The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Dashboard/Index.aspx
~/Views/Dashboard/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Dashboard/Index.cshtml
~/Views/Dashboard/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml]
System.Web.Mvc.ViewResult.FindView(ControllerContext context) +318674
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +129
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +260
System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
@James Smith - if the Dashboard views are missing then the package installation didn't occur properly. Uninstall SecurityGuard and re-install it. That should do it.
Let me know the outcome.
Thanks.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace Online_Assignment_Submission.Membership
{
public partial class WebForm1 : System.Web.UI.Page
{
const string passwordQuestion = "What is your favorite color";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
SecurityQuestion.Text = passwordQuestion;
}
protected void CreateAccountButton_Click(object sender, EventArgs e)
{
MembershipCreateStatus createStatus;
MembershipUser newUser = Membership.CreateUser(Username.Text, Password.Text, Email.Text, passwordQuestion, SecurityAnswer.Text, true, out createStatus);
switch (createStatus)
{
case MembershipCreateStatus.Success:
CreateAccountResults.Text = "The user account was successfully created!";
break;
case MembershipCreateStatus.DuplicateUserName:
CreateAccountResults.Text = "There already exists a user with this username.";
break;
case MembershipCreateStatus.DuplicateEmail:
CreateAccountResults.Text = "There already exists a user with this email address.";
break;
case MembershipCreateStatus.InvalidEmail:
CreateAccountResults.Text = "There email address you provided in invalid.";
break;
case MembershipCreateStatus.InvalidAnswer:
CreateAccountResults.Text = "There security answer was invalid.";
break;
case MembershipCreateStatus.InvalidPassword:
CreateAccountResults.Text = "The password you provided is invalid. It must be seven characters long and have at least one non-alphanumeric character.";
break;
default:
CreateAccountResults.Text = "There was an unknown error; the user account was NOT created.";
break;
}
}
ERROR :- Error 1 The type or namespace name 'CreateUser' does not exist in the namespace 'Online_Assignment_Submission.Membership' (are you missing an assembly reference?) D:\NEW PROJECT\Online Assignment Submission\Membership\WebForm1.aspx.cs 62 49 Online Assignment Submission
how to solve this error used the MVC and normal Project
@krishna - there are a couple things wrong with what I see here:
So the bottom line is you can't use SecurityGuard in anything but and MVC 3 or higher web application. The other thing is NOT to name your namespace with the word "Membership" as you will encounter this naming collision. The option with this would be to fully qualify the Membership.Create() method as System.Web.Security.Membership.Create().
And looking at this again, it doesn't look like you are using SecurityGuard anywhere in this example, so this is not a SecurityGuard issue.
I hope this helps.
@ksang - can you give me more information?
This may not be a SecurityGuard issue but rather an ASP.NET Membership system rule. SecurityGuard simply has classes built on top of the membership classes and they don't modify them. It might be a rule that usernames cannot contain characters like slashes.
Try creating a username with a dash (-) and see if you can edit it. Also try creating another username with a slash just to see if that is an issue.
The only way I can think of to fix it is to go into the database and manually modify the username and remove the slash, then see if you can edit it in SecurityGuard.
I hope this helps.
Thank you for the reply.
I can create usernames containing the forward slash like 123/2010 using securityguard dashboard and ASP.net Membership accepts it.. This is our naming convention. The usernames I create without the forward slash are editable at the dashboard but those with the slash cannot be editted. What could be the problem? Try with your database and see if it accepts because it will be difficult for us to avoid that naming convention.
@ksang - the forward slash in the username doesn't work with an MVC application because the routing engine assumes it's part of the routing mechanism. This has nothing to do with SecurityGuard, it's just an MVC convention.
I tried it and I can create the User (123/2012) but I can't edit it because of the slash in the URL.
http://localhost:51602/SecurityGuard/Membership/Update/123/2012
See how it looks in the address bar of the browser? You should really find another naming convention that will be used with MVC applications.
I hope this helps.
Hi I have installed the Security Guard MVC4 and everything is working perfectly but one thing. Everywhere in the Security Guard there is a LogOn link while MVC 4 creates a LogIn link and i have an error when I press the Log In button on the default website. I can register a user but I cannot Log In it gives me the following error:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.Requested URL: /SGAccount/Login
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
Please hel me to solve it!I am not sure but I might have solved the issue. In _LoginPartial.cshtml I changed all the strings Log in to Log on and I have been able to Login now. But when I try to LogOff this is what I get:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.Requested URL: /SGAccount/LogOff
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
Basicly the same thing but now I cannot find where to fix the issue these are my settings in _LoginPartial.cshtml:
@if (Request.IsAuthenticated) {
<text>Hello, @Html.ActionLink(User.Identity.Name, "Manage", "SGAccount", routeValues: null, htmlAttributes: new { @class = "username", title = "Manage" })!
@using (Html.BeginForm("LogOff", "SGAccount", FormMethod.Post, new { id = "logoutForm" })) {
@Html.AntiForgeryToken()
<a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>
}
</text>
} else {
<ul>
<li>@Html.ActionLink("Register", "Register", "SGAccount", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log on", "Logon", "SGAccount", routeValues: null, htmlAttributes: new { id = "logonLink" })</li>
</ul>
}
@iliali16 - yes, the Log on methods on the Membershp are different, one is LogOn and the other is Login. Originally I matched their method but then they changed it. I'll update this in a new update, but in the meantime you just need to change "Login" to "LogOn".
Regarding your "LogOff" issue, VS 2012 MVC4 projects have changed the way LogOff is handled. It changed some things such as the HTTP method (change HttpGet to HttpPost) and added the ValidateAntiForgeryToken() attribute to the LogOff action.
I'll update this in the next release.
Hi,
Great code, I like it a lot, I have a small problem, everything is working fine but when I try to LogOff I get the following error.....
The required anti-forgery form field "__RequestVerificationToken" is not present.
Is this perhaps a cookie which is not being set?
Many thanks
Phil
Thanks for the quick response working fine now.
Phil
Hi,
Thanks for making this! I was able to get most everything to work except for the manage user. When I click on a logged in user I got the error
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.Requested URL: /SGAccount/Manage
I had already updated _LoginPartial.aspx as explained above using SGAccount like so
<% if (Request.IsAuthenticated) { %>
Hello, <%: Html.ActionLink(User.Identity.Name, "Manage", "SGAccount", routeValues: null, htmlAttributes: new { @class = "username", title = "Manage" }) %>!
However, when I look in Views/SGAccount there is no Manage file. Shouldn't there be one there? I do see one in Views/Account.
Thanks,
Todd
@TParsnick - sorry you are having this problem, I see what the problem is. There is no "Manage" controller action on the SGAccount controller. This controller is just for the basic Membership commands, like Login, Logoff, ChangePassword, ForgotPassword, etc. This controller is not for managing Users.
If you are looking to manage your users accounts, then you should point the link to the "SecurityGuard/Index" action. This will take you to the main dashboard for SecurityGuard. Then you have access to all the commands in SecurityGuard.
Take a look at the "Login Partial Updates" section in this article and I show how you can make a link in your public site to point to the SecurityGuard application.
You can always look in the SecurityGuard controllers to see what controller actions are available. :^)
Does this answer your question?
hi king,
do you support the new simplemembership and mvc4? i had some difficulty getting it working and just wanted to make sure.
it works great with mvc3 and the regular membership.
thanks,
michael
King,
Thanks for answering my question about the "Manage" controller. I will use the SecurityGuard/Index action.
I hope to see your SimpleMembershipProvider soon as this would make for a nice out of the box solution for the MVC4 template.
Cheers,
TParsnick
@jtawil - you don't want to remove the controller, because then no one could Login.
If you don't want users to register themselves into your application, the first thing would be to remove all links to a Register page. Then the easiest thing to do next would be to simply add the "SecurityGuard" role to the Register action of the SGAccountController. This will prevent unauthorized users from registering.
[Authorize(Roles="SecurityGuard")]
public ActionResult Register(){
}
That should work.
If that's not what you mean, if you want them to Register, just not be activated automatically, then simply change the "isApproved" parameter to "false", in the Register POST action.
Change this:
membershipService.CreateUser(model.UserName, model.Password, model.Email, model.SecretQuestion, model.SecretAnswer, true, out createStatus);
... to this:
membershipService.CreateUser(model.UserName, model.Password, model.Email, model.SecretQuestion, model.SecretAnswer, false, out createStatus);
Then users will be able to register, but you will have to activate them in the SecurityGuard Dashboard.
I hope this answers your question.
I am having the same issue as Hugo above - MVC4 app, the ForgotPassword form only has 1 field for email address, it doesn't show the Question, nor does it have a place to type the Answer. The result is that you get an error - 'Value cannot be null Parameter name: passwordAnswer'.
I have gone into the user account using ASP.NET Configuration in VS and made sure the Question and Answer are set.
Any help would be appreciated. Great work on the app by the way! I really enjoy using it!
Mike
@Mike and @Hugo, Ok, I see what you guys are talking about. Yes, that's my faux pas. I'll look at that and fix it soon. Thanks for the catch.
Thanks for your application is very useful, however your tutorial and installation/configuration instructions are out of date, they do not provide correct instruction and this is very frustrating and a waste of time of your users. You should show some respect towards your users, and make sure that the installation and configuration instructions are up to date.
No offense. But I have wasted my time trying to figure out how to install and configure this application in order to make it work.
This is amazing work, I was actually trying to implement this exact same thing using the new simplemembership user and stumbled across your solution -I cannot thank you enough for saving me so much time and work!! Thanks again :)
Thansk for your understanding
As a beginning you may very well start by telling users how to login as an administrator, I cannot see this anywhere on the tutorial or within the code.
Thanks.
Articel is amazing.
I want to implement hierarchical role. Means if i login with Admin all roles has to display(which is happening by default) . Now if I login with Manager only specific role has to displayed and he should not have any rights to delete any roles nor create roles.
How this can be acheived ?
Or is there is any priority in roles?
@samhtc - I understand how an unfamiliar application can be a little confusing. I'll work on the article documentation so it's clearer.
Regarding your inquiry about how to login as an administrator, sorry that this wasn't clear. There is no special thing to do in order to log in as an Administrator (I'm assuming you also mean under the SecurityGuard Role). You simply log in with your administrator credentials and you will have access to SecurityGuard, as long as you haven't changed any roles in the Authorize attributes on the controllers in the SecurityGuard Area.
I show how you can create public site navigation to conditionally display a link to SecurityGuard if you log in as that Role. Logged on users who are NOT in the SecurityGuard Role will not have access to SecurityGuard.
This means that whenever anyone logs into the application, your application will pick up the Role they are associated with and respond accordingly.
I hope this answers your question.
@Karthik -
I think you are asking if different roles apart from the SecurityGuard Role can have access to SecurityGuard in order to manage users, a quick answer might be, "yes", but this hasn't been tested or implemented.
SecurityGuard was meant for a single role (SecurityGuard) that would have complete access to the entire operations of SecurityGuard. This area is meant for an Administrator to handle all user functions, not to delegate certain functions to other roles.
I'm not saying that what you want to do isn't possible, but you would have to make modifications to make it work, such as decorating some controllers with less-privileged roles in order to allow that Role to handle those operations.
I hope this answers your questions.
Thank you very much :)
Already changed few lines of codes for two levels. There are 5 levels of roles, felt bit pain in adjusting the code . So posted.
@Karthik - I did what I could in building SecurityGuard that would allow you to make modifications directly in your application without having to go into the original SecurityGuard assembly. This allows for flexibility so you can make a change to one application and not be stuck with having those changes in all future applications.
Yeah, unfortunately if something needs to be tailored to your liking, you will need to put in a little work. :^)
To all, I've posted the fixed to the ForgotPassword issue when the RequiresQuestionAndAnswer is set to "true". This is version 1.0.8 and has been posted to NuGet and I've also updated the github repository.
Any future issues you find can also be posted on the github repository.
Thanks again for bringing this to my attention.
Hey King, I've been using SG for a long time - love it. I upgraded my application from MVC3 to MVC4 recently and everything was working fine after the upgrade. Today I upgraded SG from 1.0.4 to the latest version via nuget. The installer created a new SQL connection in my web.config and applied that to all of the membership settings (well commented out my membership stuff and made new ones); it was easy enough to go in and replace all of the membership settings with the correct SQL connection. After that I made changes to use LoginPartial instead of LogonPartial. Now when I try to login I am getting an exception in the SGAccountCOntroller.cs at line 76:
The exception mentioned several columns in the Users table are not valid/found: [UserId], [ApplicationId], [IsAnonymous], [LastActivityDate]. I confirmed these are missing from my database table Users.
Was there an update to the membership database tables from Microsoft that I missed? My membership tables are from when I created my original MVC3 application.
Here is the SQL that I got from SQL Profiler that caused the exception:
Well looks like the web.config changes might have been due to some updates from MS:
http://weblogs.asp.net/jgalloway/archive/2012/08/29/simplemembership-membership-providers-universal-providers-and-the-new-asp-net-4-5-web-forms-and-asp-net-mvc-4-templates.aspx
I'm still researching changes to the database schema. I would like to know what "version" of the membership schema you are using (a link to what it should look like would be great).
@JamesB - sorry about the problem upgrading. For MVC 4 applications, I've moved to the new System.Web.Providers assemblies instead of the original System.Web.Security namespace. I do mention that the newer versions of SecurityGuard are using the System.Web.Providers namespace, but I'll update the article to point out that it has changed from the previous version of the providers.
Regarding the membership sections in the web.config file, the main difference is the providers that are used. I talk a little more about this change in my other article on my MvcInstaller package for VS 2012. That might help you understand the primary differences between the two providers.
I will update my article to point out what to do for those developers who are upgrading SecurityGuard on an application that still uses the System.Web.Security namespace.
to install package i faced to following error :
Install-Package : Could not connect to the feed specified at 'https://nuget.org/api/v2/curated-feeds/windows8-packages/'. Please verify that the packagein fact i installed these type in my vs on windows 8 and it works well but when i wanted to install this in windows 7 on vs2012 it showed that error code
and i want just know that it only works on windows 8 or not ?
thanks king i`v solved . i changed a setting in nuget and it installed well.
and a problem when user request a page that is must authenticate after login login url is null and it return to home page ?
@Behrooz - you are right, it is broken. I just fixed it and updated the github repository and the NuGet feeds. You don't need to update via NuGet to make this work. Simply open the Login.cshtml (or the WebForms version if that's what you are using), and make the Html.BeginForm() look like this:
@using (Html.BeginForm((string)ViewBag.FormAction, "SGAccount", new { returnUrl = Request.QueryString["ReturnUrl"] }))
Thanks for pointing this out.
Thanksssssssssssssssssssssssssssssssss! it works properly OK
I Love you king
Dear King Wilder,
First of all I would like to thank you for the SecurityGuard and the effort you put to create it. I haven't been using it long time but I really like it, especially the fact I don't have to invent the wheel again :) However, I have encountered one problem using your package -- I'm Polish and I tend to write applications in my native language so if I want to use the SecurityGuard I've got two options: leave it in English or translate every single label. I was wondering if you could take into consider putting all strings such as labels in views, custom error messages in models etc. in a resource file. I think it would be great improvement for the people writing multilingual applications.
Secondly, I don't know whether you've updated something recently, but when installing SecurityGuard package via NuGet, additional Area is being added called SGMembership and I suppose it contains duplicated Views, also ViewModels are duplicated. As a result I cannot build my solution because following errors occur: The namespace 'SecurityGuard.ViewModels' already constains a definition for '[ViewModelName]'. When I deleted SGMembership Area and the duplicated view models, my solution has been build successfully.
Lastly I would like to about the licence -- can I use the SecurityGuard in commercial use or it's only for personal use?
Regards,
Adam
@Adam - I'm glad you like the application. My responses follow:
Thanks.
I should say wonderful job
I have one little question how did you create your user that you assigned to the SecurityGuard role.
Thanks
@hamsaya - I'll answer your questions:
Once you apply these things, you should have no problems. Enjoy.
Thanks for your response, I actually did come up with another solution.
What I did was I authorized Administrator to access the controllers SecurityGuard had access to.. in MVC installer I had only 2 roles Administrator and Manager...
I thank you for this great work... and I will recommend this to all my fellow developers.
@hamsaya - in MvcInstaller you have the ability to add any number of Roles that you need for your application, including the SecurityGuard Role. But since you didn't, that's ok, you have it working now. But I would not include the Administrator Role on the SecurityGuard controllers.
Here's what I would do for better security:
That's my suggestion. Have fun!
I was thinking of something on the same line as you mentioned. You have done a fantastic job of creating this interface. If I happened to come up with something to contribute I will definately let you know ...
Thanks a bunch !
hi king
in another try i installed securityguard without change just change in connection string and i`m sure that connection string is correct
after run i faced to this problem : The provider did not return a ProviderManifestToken string in this method Register(viewModels.RegisterViewModel model)
or any other method dose same as this error . i mention again that i installed security guard orginaly and just change is in connection string which i`m sure it is correct becuase i coyed connection from another program
king if it be needed i can send my web.config file to you
Hi,
i have managed to get this installed and working, but have an issue when adding usernames with . or @ signs in, seems as i was wanting to use the email address as the username, i am having issues, it lets me create the users but when i try to edit or update/ or add to role i get a 404 error page.
kind regards
On account Manage I get this error ... Account/Manage .. I get the following error..
To call this method, the "Membership.Provider" property must be an instance of "ExtendedMembershipProvider".
I noted others having the same problem. I re installed the MVC 4 didn't work :(
It was working fine all of a sudden just stopped working ..
Hi,
I installed SecurityGuard (for MVC3) but when I do all the configuration and try to logon, the logon page is empty. Any idea what goes wrong?
Kind regards.
@johwil - sorry I don't know why the Logon page is empty. Have you looked at the page to see if it contains any code? Can you give me more information?
You can always try to uninstall the package and re-install it.
I installed SecurityGuard for MVC3
The url for the logonlink is SGAccount/Logon. The page is realy empty (checked with FireBug). It contains only the basic html tags like <html><head></head><body></body></html>
I installed and reinstalled SecurityGuard multiple times. I found one problme with the installation (in an existing project). The installation installs ALL the controlers twice. One in Area/SecurityGuard/Controllers and once in Controllers. In order to make the application build, I have to remove aal the SG controllers from the Controllers folder. If I do not modify the _partial_login.cshtml page, to point to SGAccount (keep Account), I can login to the application and the SecurityGuard dashboard is available. Most of the functionality also works fine (except listing the roles). If I continue debugging, working with roles works as expected.
Kind regards
@johwil - this is new! Is this a brand new project you are building in VS 2010, or are you adding SecurityGuard to an existing application? If it is brand new, where you haven't started writing any code yet, I would simply delete everything and start again. You should not be having these problems.
Upon installation, everything is installed in the location that they should be, so the SGAccount Controller SHOULD be in the /Controllers folder, not in the SecurityGuard Area, if that's what you are thinking.
Also, don't check the Logon page with Firebug, actually look in the /Views/SGAccount folder and open the file to see if it has any markup. It should.
Have you watched the video showing me install and use SecurityGuard? If not, take a look and see if you are doing something wrong. I use it on every application I build and I'm literally up and running in minutes.
You will most likely be able to use the Account Controller to log into the SecurityGuard Area as long as the SecurityGuard Role is created. But the SGAccount Controller has modified the commands for account management to make them work in a more enhanced manner than the default Account Controller, so you should use that for authentication and account management.
I suggest you do this as a test:
This should give you a nice clean application with SecurityGuard successfully installed. This whole process should take you no more than 5 minutes. Once you see how this application is working, you should be able to go back and make adjustments to your other application.
Let me know how it goes.
Hi,
On quick update (I did not have access to the computer with the project while writing above update). It is not the controllers that are created twice, but the Models.
Hi,
Installing SecurityGuard in a new project gives this output:
PM> install-package securityguard
Successfully installed 'SecurityGuard 1.0.53.586'.
'Views\SGAccount\Register.cshtml' already exists. Skipping...
'Views\SGAccount\Register.aspx' already exists. Skipping...
'Areas\SecurityGuard\Views\Membership\CreateUser.cshtml' already exists. Skipping...
'Areas\SecurityGuard\Models\RegisterViewModel.cs' already exists. Skipping...
Successfully added 'SecurityGuard 1.0.53.586' to MvcApplication3.
PM>
And again, the installation process creates all the models twice, once in <Project>/Area/SecurityGuard/Model and once in <Project>/Model
Which one should I delete
@johwil - ok I just looked at the NuGet package for Mvc3 installations, and you are right. I goofed! I'll fix that real quick.
Here's how you can easily fix it in the meantime.
Build the application and it should work fine now. Sorry about that. Let me know how it turns out.
Hi,
I installed SecurityGuard (new version ;-) ) in a copy of the original application and the installation went fine (no more errors, no more doubles) thankyou for this.
When I do the necessary setup (delete the one line in weg.config), delete the .aspx pages and change Account to SGAccount in _LogOnPartial.cshtml, I still don't get a logon page (the url is:http://localhost:28197/SGAccount/LogOn?ReturnUrl=%2fSGAccount%2fLogOn)
@johwil - I don't know why this is happening. If you click on the "LogOn" link, doesn't it take you to the Logon page? It seems you have something else going on here. Do you have any "location" sections in the web.config file? Is there anything that is restricting ALL unauthenticated resources? If you have the entire application restricted to only authenticated users, then you might need to allow anonymous users to access the /Views/SGAccount folder.
Otherwise, I don't know why this is occurring.
Thank you, Anonimous acces to the SGAccountController did it.
Thank you very much for your patience.
hi king if you remember i`v sent an email to you to discover my problem ?
@twun - sorry for the delay, I completely missed your post. Regarding your problem updating users with usernames as email addresses, what version of Mvc and SecurityGuard are you using?
I was able to successfully create a user with the username as an email address, and then instantly assign the user to a role without issues. I was also able to update the user's information, and then revoke the user from the role.
I did this with an Mvc4 project using SecurityGuard 1.0.8. Let me know.
hi king and thanks a lots for your response i think my problem must be in web.config this is web.config content that work withs security guard and it works very well after change some option such as : type in membership tag and roles please take attention with those
<configuration><configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<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" providerName="System.Data.SqlClient"
connectionString="Data Source=B-AMIRINEJAD\SQLSERVER2012SC;User ID=abhrcome;Password=123456;Initial Catalog=MVCDB;Integrated Security=true" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="MvcMailer.BaseURL" value="" />
<add key="SecurityGuardEmailFrom" value="info@email.net" />
<add key="SecurityGuardEmailSubject" value="Your Password has been reset." />
<add key="SecurityGuardEmailTemplatePath" value="~/MailerTemplates/ResetPassword.html" />
<add key="AppInstalled" value="false" />
</appSettings>
<system.web>
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.5" />
<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.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<authentication mode="Forms">
<forms loginUrl="~/SGAccount/Login" timeout="2880" />
</authentication>
<profile defaultProvider="AspNetSqlProfileProvide" enabled="true">
<providers>
<add name="AspNetSqlProfileProvide"
type="System.Web.Security.SqlProfileProvider"
connectionStringName="DefaultConnection"
applicationName="/" />
</providers>
</profile>
<!--<membership>
<providers>
<clear />
<add name="DefaultMembershipProvider"
type="System.Web.Providers.SqlMembershipProvider"
connectionStringName="DefaultConnection"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="DefaultRoleProvider">
<providers>
<clear />
<add name="AspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="DefaultConnection"
applicationName="/" />
<add applicationName="/" name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</roleManager>-->
<membership>
<providers>
<clear/>
<add name="AspNetSqlMemberShipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="DefaultConnection"
requiresQuestionAndAnswer="false"
applicationName="/"
minRequiredPasswordLength="5"
minRequiredNonalphanumericCharacters="0"
enablePasswordReset="false"
requiresUniqueEmail="false"
/>
</providers>
</membership>
<roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">
<providers>
<clear />
<add name="AspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="DefaultConnection"
applicationName="/" />
</providers>
</roleManager>
<!--
If you are deploying to a cloud environment that has multiple web server instances,
you should change session state mode from "InProc" to "Custom". In addition,
change the connection string named "DefaultConnection" to connect to an instance
of SQL Server (including SQL Azure and SQL Compact) instead of to SQL Server Express.
-->
<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>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<system.net>
<mailSettings>
<!-- Method#1: Configure smtp server credentials -->
<smtp from="some-email@gmail.com">
<network enableSsl="true" host="smtp.gmail.com" port="587" userName="some-email@gmail.com" password="valid-password" />
</smtp>
<!-- Method#2: Dump emails to a local directory -->
<!--
<smtp from="some-email@gmail.com" deliveryMethod="SpecifiedPickupDirectory">
<network host="localhost" />
<specifiedPickupDirectory pickupDirectoryLocation="c:\temp\"/>
</smtp>
-->
</mailSettings>
</system.net>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
@Behrooz - I see the problem, look at the article again. I mention in the "Pre-requisites" that SecurityGuard uses the System.Web.Providers assembly, not the prior System.Web.Security assembly.
Probably the easiest way to get the site configured is to install MvcInstaller.Mvc4. It will place the correct Membership sections in the web.config for you.
I would suggest you completely delete all of the Membership sections from the web.config and then install the MvcInstaller.Mvc4 NuGet package. You'll see that it will install all the necessary configuration for you. But it will probably also install a second connectionStrings section. So you might get two "DefaultConnection" connection string elements. Delete one of them and run your application. It should all work then.
Also pay attention to the ApplicationName in the various membership sections. They need to match the application name in your database. If it doesn't you won't be able to log in.
Give that a try.
hi king and sorry again i hosted my application under IIS and on browse time it shows me an error
The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the <machineKey> configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster.
@behrooz - I'm not sure what this message means.
Hi King,
i was using 1.0.9 and MVC4,
twun
i had another look and resolved this myself, it wasn't a problem with securityguard, it was to do with having . (period) in the url.
i had to add a handler to deal with this in the webconfig, so it gets treated as a MVC URL.
<handlers>
<addname="UrlRoutingHandler"type="System.Web.Routing.UrlRoutingHandler, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"path="/SecurityGuard/*"verb="GET"/>
</handlers>
verb="*"/>
so that it catches the posts too.
Hi King,
Thank you for creating this wonderful membership management system. I was able to follow the instructions and installed them on my sample application. I really like it. However, I found an issue with the system and wanted to bring this to your attention. When I clicked on my name to manage the profile, I got an error message. Please see the error message below. I checked the SGAccountController and could not find this action, "Manage". Please let me know.
Server Error in '/' Application.
Description:The resource cannot be found.
HTTP 404. The resource you are looking for (or one of its dependencies)
could have been removed, had its name changed, or is temporarily unavailable.
Please review the following URL and make sure that it is spelled correctly.
Requested URL: /SGAccount/Manage
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET
Version:4.0.30319.17929
Thanks,
Kiri-
@kiri - you are getting this message because the Manage action is not part of SecurityGuard. It's part of the default AccountController that is installed with the Mvc template in Visual Studio.
You would need to change the _LoginPartial.cshtml to remove that link, or have it point to the SecurityGuard Area instead.
If you look in the Manage View and Manage Action of the controller, you'll see what it does. In essence it's trying to be a mini-Administrative page. It's giving you the ability to Change the Password, and a couple other things. The important things like ChangePassword are included in SecurityGuard so you can completely remove this and just use the commands in SecurityGuard.
I hope this answers you question.
Hi King,
Thank you for the quick response. I have removed the line from the _LoginPartial.cshtml for now. I will go through the code again to understand what it does exactly later. Once again, thank you for the wonderful membership management system. This is what exactly I was looking for.
PS: May be you may want to update your help document to reflect this. I was basically following your instructions for installing it. Later I found the video as well. Very nice tutorial like the one from Bob Tabor and Scott Hassleman.
Cheers!
Kiri-
Hello, King Wilder!
I have a problem.
For example, on this page SecurityGuard/Membership/Update/bizuser superadmin can set a new email address, comment.
I need to superadmin could give the new password to the user whithout old password.
I know this violates the whole security policy, but it should be.
How need add new textbox, and input for this textbox new password?
But have a resetPassword() method...
Maybe work with this method, but I don't work yet.
@Temirlan - I have not built any functions like this into SecurityGuard yet. The source code is available to you in the meantime if you want to add that feature yourself.
I would not include this feature in the details page for the user, I would create a new page just for this purpose. This way you aren't modifying any existing functionality, you are just adding to it. The ResetPassword method could be added to this new functionality.
I may get around to adding this feature if I think the community would like it.
Hello, I do next...
In MembershipController at method UpdateUser I'm add a code user.ChangePassword(user.ResetPassword(), "testPassword") before try...catch block.
And now If superadmin click to button "Update" in Manage User panel, to DB send new password "testPassword"
Now I work, give random password, and display into a Update.cshtml file.
I hope finished it
Create in MembershipController random password generator before try...catch block.
UserViewModel model = new UserViewModel();
model.RandomPassword = Membership.GeneratePassword(12, 1);
user.ChangePassword(user.ResetPassword(), model.RandomPassword);
And in UserViewModel new property public string RandomPassword { get; set; }
And I cannot, display my new random password at Update.cshtml @Model.RandomPassword don't show the random password
I solved this problem.
In MembershipController add this code
#region Random Password
[HttpGet]
public ActionResult RandomPassword()
{
return View();
}
[HttpPost]
[MultiButtonFormSubmit(ActionName = "UpdateDeleteCancel", SubmitButton = "RandomPassword")]
public ActionResult RandomPassword(string UserName)
{
MembershipUser user = membershipService.GetUser(UserName);
string newPassword = Membership.GeneratePassword(8, 0);
newPassword = Regex.Replace(newPassword, @"[^a-zA-Z0-9]", m => "9");
ViewData["randomPass"] = newPassword;
user.ChangePassword(user.ResetPassword(), newPassword);
return View();
}
#endregion
Create new View. To Update.cshtml add next <input type="submit" value="New password" name="RandomPassword" /> in 170+ line of code
King Wilder, I never upload code to github before, please give instruction and I add this functional.
@Temirlan - your code looks ok, but I think you are re-inventing the wheel. If you wanted to allow Administrators to either Reset the users password, or change it to something prescribed in the SecurityGuard Dashboard, you do either of the following:
1) ResetPassword
MembershipUser user = membershipService.GetUser(userName);
string newPassword = user.ResetPassword();
2) ChangePassword
MembershipUser currentUser = Membership.GetUser([enter the user name here], true /* userIsOnline */);
bool changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
Again, I would probably create a new view for this so I'm not altering any existing functionality. It makes upgrades easier.
This should be fairly easy to apply. I might even add it to the next version. Thanks for bringing this idea to me. You will get credit.
Has anyone added the external logins to the securityguard interface ie facebook, google, etc.? I was wondering what steps you took to make that work. Is it just a matter of adding the section to the SGAccount login view and copying the accountController methods to the SGAccountController?
Thanks,
Mike
Hi King,
I am kinda new to MVC. I have installed MVC4 and downloaded SecurityGuard. Everything looks fine in the begining, I am able to login. When I try to manage users or create user through dashboard, I am getting strange exception. Somehow, it is trying to load MVC 3 library.
Could not load file or assembly 'System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
This happens only for "Manage Users" and "Create User". Do you have any idea? I have checked all the config files but there is no MVC 3.0.0.0 is loaded for any application.
Thanks in advance for your support.
Yildirim.
@yigu - I don't know why you are getting this error. Try this, open your project in Visual Studio and open References and right-click on the System.Web.Mvc assembly and check the Properties. See what version is says it is.
Did you install the SecurityGuard.Mvc4 NuGet package?
Thats is great thanks :D
I want to do that throw display on the GUI. If it possible? If yes tell me please, what direction I need to chose
Can I do this not through the code in the controller. Can I do this through GUI?
Hello,
Thank you for such a nice SecurityGuard implementation.
I am using SecurityGuard in my application. I have created one user with "SecurityGuard" role rights but when I try to login to the application using that User I am getting following error,
Server Error in '/' Application.
--------------------------------------------------------------------------------
The view 'index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Dashboard/index.aspx
~/Views/Dashboard/index.ascx
~/Views/Shared/index.aspx
~/Views/Shared/index.ascx
~/Views/Dashboard/index.cshtml
~/Views/Dashboard/index.vbhtml
~/Views/Shared/index.cshtml
~/Views/Shared/index.vbhtml
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.InvalidOperationException: The view 'index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Dashboard/index.aspx
~/Views/Dashboard/index.ascx
~/Views/Shared/index.aspx
~/Views/Shared/index.ascx
~/Views/Dashboard/index.cshtml
~/Views/Dashboard/index.vbhtml
~/Views/Shared/index.cshtml
~/Views/Shared/index.vbhtml
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:
[InvalidOperationException: The view 'index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Dashboard/index.aspx
~/Views/Dashboard/index.ascx
~/Views/Shared/index.aspx
~/Views/Shared/index.ascx
~/Views/Dashboard/index.cshtml
~/Views/Dashboard/index.vbhtml
~/Views/Shared/index.cshtml
~/Views/Shared/index.vbhtml]
System.Web.Mvc.ViewResult.FindView(ControllerContext context) +506
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +230
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +74
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +388
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +72
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +303
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +155
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +184
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +66
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +40
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +68
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +65
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +45
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +66
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629708
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929
Can you please help me to resolve this issue? As it is very urgent for me resolve this.
Thanks,
Nehali
I uninstall and reinstall the SecurityGuard, but stiill facing the same problem. :(
Oh! It was my mistake. I was trying to navigate the application to wrong URL. Now it is working.
Thank you so much for creating such a nice thing. It is really very helpful.
Yes that is I mean. =)
Ok. Thank you
Very nice app, needs work!
1. SecurityGuard MVC 3
- Need same Views & Controllers as SecurityGuard.MVC4 (Dashboard, etc...)
- Need database. (consider a person needs a quick security solution and no time to build a database. New LocalDb would be nice!)
2. SecurityGuard MVC 4
- Much nicer than previous MVC 3 version
- Again, like the MVC 3 version, needs a database (LocalDb).
@Pointeman - I'm glad you like it. What views and controllers are you talking about specifically? There is only one view that I have not yet included in the Mvc3 version and that's the EnterSecretAnswer.[extn]. But everything else is the same.
Regarding the database, I do mention in the article that SecurityGuard does not install any database or database tables. You should already have the ASP.NET Membership system installed in your database. SecurityGuard was built simply as a quick way to provide a web interface so you can manage your already installed Membership database.
To install the ASP.NET Membership system quickly and easily, you can look at my other NuGet package called MvcInstaller. I've built these two packages to work together (or separately). MvcInstaller can not only install the ASP.NET Membership system for you, but it can populate it with the users and roles for your Administrator so you immediately have access to manage it, and configure the application's web.config and connectionstring for you. MvcInstaller, can also install your application's database schema for you.
I don't really see the need to have a LocalDb created with SecurityGuard since you most likely will be using SecurityGuard to manage users for an application that has a database schema, and the Membership system can be installed in that database.
If you prefer to have the Membership system as a separate database from the application's schema, MvcInstaller can do that for you also.
I am open to feature suggestions and I do appreciate your comments.
Thanks.
Half the time, the passwords emailed are not correct and users cannot login.
Are you properly escaping HTML characters in the emails?
@dude - are you talking about getting the passwords using the "Forgot Password?" feature? If so, I'm not doing anything out of the ordinary. I just reset the password, using the default Membership methods, and then sending it off to the user. The Membership provider can't decrypt the password and send it to the user, it just creates a new one and I send it to the user. Look at the SGAccount controller, all the code is there for how the ForgotPassword function works.
Hopefully this answers your concerns.
Hello nice job!
I'm trying to figure out if this Package with others databases as well like Azure and SQL Compact, if so what changes are neccesary in order to achieve the connection with your package and said databases
Thanks in advance
Hello nice job!
I'm trying to figure out if this Package can be used with others databases as well, like Azure and SQL Compact, if so what changes are neccesary in order to achieve the connection with your package and said databases
Thanks in advance
@jctt - I have not tested it with either Azure or SQL Compact. I'm not sure how Membership is handled with Azure, but I don't think it's much different if at all.
For Azure I would make sure you have the Membership database created and SecurityGuard is installed in your application, and then publish it to Azure using your Azure connection string. Of course update your web.config membership section with the Azure connection string, but in theory, that should work.
One of these days, when I have time, I'll investigate seeing if it can work with Azure.
As for SQL Compact, this should also be possible, but you would need to have the Membership database installed in the SQL Compact database. Then again its just making sure you have the connection string in the Membership section pointing to the correct database, and it should work.
If you try this, I'd like to hear what your results are. I hope this helps.
Hi Wilder,
Thank you very much, I managed to install Security Guard with SQL Compact! It was a matter of just changing the connection string.
Since I started the project for the first time, creating and MVC4 with VS2010, I had to follow these steps
1) in the PM run "install-package system.web.providers"
2) Use ASP.Net Configuration tool, to create the Roles and Users.
Without these steps I end up having the message To call this method, the "Membership.Provider" property must be an instance of "ExtendedMembershipProvider".
@jctt - I'm glad you got it to work.
If you have other MVC applications that you build that use SQL Server, rather than SQL Compact, you can use my other NuGet package called MvcInstaller to install your database schema and the ASP.NET Membership system, with your Roles and Users. It's quick and clean. Check out my other articles and video on MvcInstaller. It also includes System.Web.Providers for you.
I did checked the others articles and videos, it was nice reading thank you very much! it help me understand the Membership System Provider of ASP Net. Before this I knew nothing about it.
I also though about connecting a new MVC4 Project with an existing MySQL Database, so I followed the same steps of this article. But I have to install the Microsoft ASP.NET Universal Providers Core Libraries with the "Install-Package Microsoft.AspNet.Providers.Core". just have to make sure to install the mysql libraries and modify the connection string like this
<connectionStrings>
<add name="MySQLConn" connectionString="Server=localhost;Database=dbname;Uid=username;Pwd=password;" />
</connectionStrings>
And when you run the above command, the package will make the neccesary changes to the membership sections of web config.
In sum,
1. Install MySQL.Data (6.6.4.0) and MySQL.Web (6.6.4.0)
2. Run "Install-Package Microsoft.AspNet.Providers.Core" with PM
3. Go to Project Menu -> ASP.Net Configuration, Go to Provider Tab, Make sure to select MySQL Membership Provider.
4. Enjoy Security Guard!
Note: I actually performed all these steps after installing Security Guard. I didn't test the other way around though. Also I ran into something I will expand in the next post.
Anyway thanks a lot! That was a fantastic job.
The other thing, is that when I want to add a new role to the user, namely "SecurityGuard" and "Manager", sometimes It displays this message "There was a problem adding the user to the roles.", and sometimes it accepts the new settings after few retries.
So I'm not sure it that is related with MySQL??
@jctt - nice work getting it to work with MySql. I never tested it with that database, I'm glad you figured this out.
Regarding adding the Roles, I've never had a problem adding a role to a user. This might be due to MySql. If you actually have the ASP.NET Membership database inside the MySql database, there could be an issue, but I don't know what it could be. This would be an ASP.NET Membership issue with MySql, not an issue with SecurityGuard.
You might want to post a message in the asp.net Forums about this.
first it is very nice and work fine but when i do log off i got error
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.Requested URL: /SGAccount/LogOff
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18034
but if i go to address line and i press enter is
do the logout , or if i not use the " @Html.AntiForgeryToken() " but i use the same logoff in
_SecurityGuardLayoutPage.cshtml the logoff work Thamks
hi
i repkace the line " <a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>" withe the line " @Html.ActionLink("Log Off", "LogOff", "SGAccount", new { area = "" }, null)" and it is work ' there is problam with the replace?
i resolve the problam with change this code in SGAccountController in the public virtual ActionResult LogOff() function
from
[HttpGet]
[HttpPost]
public virtual ActionResult LogOff()
{
authenticationService.LogOff();
return RedirectToAction("Index", "Home");
}
Thanks for your answer .
as you can see i installed the right ver.
but never minde now it is work.
here the change that work
function OnGetUsersInRoleSuccess(data) {
ul.empty();
if (data == "") {
ul.append("<li>No user(s).</li>");
} else {
$.each(data, function (index, item) {
var ref = '@Url.Action("Update", "Membership")';
ref = ref + "/";
ul.append("<li><a href=\ " + '"' + ref + item + "\">" + item + "</a></li>");
// ul.append("<li><a href=\"/SecurityGuard/Membership/Update/" + item + "\">" + item + "</a></li>");
});
}
}
'MvcInstaller.JsonResponse' does not contain a definition for 'CssClass' and no extension method 'CssClass' accepting a first argument of type 'MvcInstaller.JsonResponse' could be found (are you missing a using directive or an assembly reference?) \Areas\SecurityGuard\Controllers\RoleController.cs 54 26
can u help me?
In MvcINstaller.JsonResponse metadata, I have:
#region Assembly MvcInstaller.MVC4.dll, v1.1.0.0// D:\xxx\xxx\packages\MvcInstaller.MVC4.1.1.1.0\lib\net40\MvcInstaller.MVC4.dll
#endregionusing System;
namespace MvcInstaller
{
public class JsonResponse
{
public JsonResponse();
public string Message { get; set; }
public bool Success { get; set; }
}
}
@Ivo - what you probably did was bring in the wrong "using" reference for the JsonResponse class. If you have the following at the top of your RoleController class:
using MvcInstaller;
... remove it and it will probably work. You had a conflict with the JsonResponse classes that are in both assemblies. Give that a try.
Hi, King
thank you for great job.
when I install in MVC4. and point connection string to my exist database schema. it give me a warning !
my web.config
<connectionStrings>
<add name="MembershipConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SchoolV1;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="MyCoolEntities" connectionString="metadata=res://*/MyCoolEntities.csdl|res://*/MyCoolEntities.ssdl|res://*/MyCoolEntities.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;Initial Catalog=SchoolV1;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework""
providerName="System.Data.EntityClient" />
<add name="MySampleConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SchoolV1;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="AppInstalled" value="false" />
<add key="MvcMailer.BaseURL" value="" />
<add key="SecurityGuardEmailFrom" value="info@email.net" />
<add key="SecurityGuardEmailSubject" value="Your Password has been reset." />
<add key="SecurityGuardEmailTemplatePath" value="~/MailerTemplates/ResetPassword.html" />
</appSettings>
I stuck there. don't know what to do. Can you please point the problem?
@Frank - firstly, this is an MvcInstaller question, not a SecurityGuard question, but I'll try to answer it anyway. Everything looks like it should work, except I haven't tested it with SQLExpress in years, and to be honest I don't remember if there were issues with it.
Can you use the Standard SQL Server database? I'll give it a test later today and see if I have any issues.
Hi, King Thanks for you response promptly. I watch your video on MVCInstaller. and redo the web.config . Now it works fine.
I use SQLEXPREES, VS2012, Mvcinstaller.MVC4, SecurityGuard.MVC4.
thanks so much.
Great System!!!
Question about ForgotPassword - when i click on that link it just continually redirects me back to home page - Have I missed a setting that allows that page to not be trapped by authorization or should there be an explicit route set? Thanks!
Server Error in '/' Application.
Could not load type 'SecurityGuard.Services.MembershipService' from assembly 'SecurityGuard, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
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.Line 37: this.authenticationService = new AuthenticationService(membershipService, new FormsAuthenticationService()); Line 38: this.formsAuthenticationService = new FormsAuthenticationService(); Line 39: } Line 40: Line 41: #endregionSource File: c:\Projects\CSI\SecurityGuard\SecurityGuard\Controllers\SGAccountController.cs Line: 39
@sandeepkoushik - I've never seen this error before. You can try uninstalling the package and re-installing it and see if that fixes the problem.
I assume you do have the ASP.NET Membership providers installed in your application, correct? If not, you need to install them.
What version of MVC are you using? What version of SecurityGuard are you using?
Hi I am using MVC 4, MVC installer 4 and Security Guard 4. How to install ASP.Net Membership providers ?
Thanks,
Sandeep
I'm new to learning programming
I can update mail address and comments to a user, can I/Administrator change the password to the users?
can you help me? Users can update email address?
@LailaMaz - At the moment, the Administrator cannot change the password to the user. The user can do that after they log in using the Change Password feature.
Users have to notify the Administrator to change the email address. Users should NOT have access to SecurityGuard. SG is for Administrators.
If you want other capabilities, you have all the source code so you can create them yourself.
I hope this helps.
@Vipul Bhavsar - SecurityGuard simply provides a means to manage your Users and Roles through a web interface. When you create a Role, it's no different than the standard ASP.NET Membership providers, you still have to provide the mechanism where that Role means something in your application, by either attaching it to the controllers, and/or actions manually.
So in other words, there is no built-in way of assigning roles to actions or controllers. That's still up to you.
I hope this helps.
What would I have to do different to make your code work if this is an Intranet based application? Also, I guess I didn't phrase my question properly previously. I am looking for a web interface to allow the user of the website to create a role and assign multiple "actions" to it. For example,
[Authorize(Roles="Data Entry, Administrator")]public ActionResult Index()
{}
Currently, I would have to hard code the roles in my code. I want the user to have the ability to create multiple roles and then allow them to associate that with the method (actions). I would pre-define the actions that they can pick, but the user would have the ability to assign as many actions they want to a particular role. Do you have any code that will do that?
@Vipul Bhavsar - re: intranet based application - this is not tested. You can try it by changing the "forms" element in the web.config to "Windows" Authentication from "Forms" authentication, and point the connection string to the Active Directory.
Re: Roles - first of all it seems weird to allow users to create Roles. To me that should be an Administrator only function, but that's my two cents. The bottom line answer to your question is, No, SecurityGuard doesn't do what you want, out of the box. You have the source code so you can make whatever modifications you want to make it work.
Again I don't really understand what you want to achieve, but it seems more logical to have specific Roles already created by you (the Administrator), and then assign them to the actions. Then assign Roles to specific Users. Then these Users will only have access to the Roles they've been assigned to, and therefore only to the controller actions that they are assigned to.
If you really need what you are asking, then you'll have to come up with a manner in which to make it work.
SecurityGuard was built as a quick way to put an interface on the Membership system, and that's all. Anything else is left up to the developer.
I hope this helps.
http://www.mindstick.com/Articles/f769698f-fed6-43eb-8e61-d7baaf713819/
http://msdn.microsoft.com/en-us/library/ff398049(v=vs.100).aspx
The file '/Views/Shared/Site.Master' does not exist.
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SecurityGuard.ViewModels.LogOnViewModel>" %>
If I have to debug it, then it is no longer SecurityGuard.
@parkstech - sorry you are having problems. I just want to be sure you did the correct thing, the code you show is for .ASPX views. This means you should have a Site.Master in your Shared folder that you are using for your site, correct? And I assume you deleted all the Razor views. If this is the case, then I don't know why you are having this problem.
I suggest doing one of two things:
This is really not a SecurityGuard issue, your application simply cannot find the required Site.Master.aspx file. Let me know how it turns out.