SecurityGuard - NuGet Package for the ASP.NET Membership system
December 1, 2014 Update!
There are some minor fixes to Mvc4 and Mvc5. It's probably easier to do these manually. Information can be found here.
New!!! SecurityGuard.Mvc5 information here.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.
Update for MVC 5
March 24, 2014
If you are installing SecurityGuard.MVC4 in an MVC 5 application via Visual Studio 2013, you will initially get an error when navigating to SecurityGuard. It has to do with the newer version of the System.Web.WebPages.Razor assemblies used in MVC 5.
The error will be something along the lines of:
assembly's manifest definition does not match the assembly reference
Until I have time to create a new version, you can easily fix this by changing the version yourself.
Go into the /Areas/SecurityGuard/Views/web.config and in the config sections, change the Razor version from 2.0.0.0 to 3.0.0.0. That will fix the issue.
On a related note: for SecurityGuard to work, you must be using the database schema that works with the System.Web.Providers assemblies. MVC 5 initially works with the Microsoft Identity system and does not have any Membership config sections in the web.config, so you need to make sure you add those sections for SecurityGuard to work.
MvcInstaller can do that for you. Check my other article on how to use MvcInstaller.
SecurityGuard does NOT work with the Microsoft Identity providers! See this article for more information on the Future of SecurityGuard.
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 rocks! 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, @User.Identity.Name!
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. A 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: #endregion
Source 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.
Dear: You have done an awsome job
Do you have any other suggestions on how to get this to work on an Intranet site? I changed the authentication part in the web.config file to this:
<authentication mode="Windows"><forms loginUrl="~/SGAccount/Login" timeout="2880" />
</authentication>
I just created a blank mvc 4 Intranet project using visual studio 2012
And I get this error:
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
@vipul30 - two things - 1) this error tells you the problem. You should only have one system.web/authentication section. If you do only have one, make sure you have the section tag closed properly, 2) SecurityGuard was never built for Windows Authentication.
Windows Authentication works with Active Directory, and SecurityGuard wasn't built for that datastore. You may need to find a different alternative than SecurityGuard for your web-interface for Windows Authentication.
I. Love. You!
I cannot begin to express how much you just made my work so much easier. Thank you for this work and for staying active with the project. It is truly priceless.
Michael Fouquette
@nnash - Hi, unfortunately I don't have any examples using the Express versions of Visual Studio, or the 2013 preview version. I ALWAYS use SQL Server standard, and never SqlExpress in my demos.
What problems are you having specifically?
Hey,
Have it all installed and working. You might want to change you installation instructions slightly as if you are using VS 2010 with MVC4 you need to follow the VS 2012 instructions (which work in VS 2010 with MVC4). Also, it wasn't entirely clear how to create the SuperAdmin user / Security Guard role. I used WSAT in the end.
There's an issue when you require unique email addresses, and you create a user from the SuperAdmin account (part of the SecurityGuard role).
This code:
public virtual ActionResult CreateUser(viewModels.RegisterViewModel model)
{
MembershipUser user;
MembershipCreateStatus status;
user = membershipService.CreateUser(model.UserName, model.Password, model.Email, model.SecretQuestion, model.SecretAnswer, model.Approve,
out status);
return routeHelpers.Actions.GrantRolesToUser(user.UserName);
}
returns a null user, and status has an error code. I think you need to check status here and display some error if there's a problem.Thanks
@Rick - thanks for your response. Can you tell me specifically needs to be changed in the instructions for VS2010? Both of these versions use the System.Web.Providers framework.
SecurityGuard is just a web-interface for the ASP.NET Membership system, it won't intially create admin users for you. You'll need to use WSAT (like you did) or use my MvcInstaller application which will do that for you. I've built these two NuGet packages to work together, one sets up the Membership system with users and roles, and the other one allows you to manage the users.
Re: unique email address issue - I'll check that out. I haven't had a problem before but I'll look into it.
Maybe I have an updated MVC4? I had to change per your LoginPartial Update section if I rememebr correct. There's definitely a bug in that code - user is returned as null, and Status has a value indicating that the email address was not unique. Because user is null the following line fails onviously.
Note this was done when adding users when logged in as the SuperAdmin - I didn't test it yet with a user requesting their own account.
I'm not stuck on getting the email to send for a new password.
You have this:
public virtual ActionResult ForgotPassword(ForgotPasswordViewModel model)
{
SmtpSection smtp = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp"
// Set the MailerModel properties that will be passed to the MvcMailer object.
// Feel free to modify the properties as you need.
MailerModel m = new MailerModel();
m.UserName = user.UserName;
m.Password = newPassword;
m.FromEmail = smtp.From;
m.Subject =
ConfigSettings.SecurityGuardEmailSubject;
m.ToEmail = model.Email;
Mailer.PasswordReset(m).Send(); I don't see how that SMTP object ever gets used to send email. Also, my SMTP server requires authentication to send - how would I set this up? Thanks
Sorry for typos in previous post- I meant I cannot get the email to work. For the reord, when I create an MVC4 internet app. in VS 2010 I get this
@
if (Request.IsAuthenticated) {
<text>
Hello, @Html.ActionLink(User.Identity.Name,
"Manage", "Account", routeValues: null, htmlAttributes: new { @class = "username", title = "Manage" })!
@
using (Html.BeginForm("LogOff", "Account", 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", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
@Rick - I'll try to answer each post...
When I get a moment, I'll test creating a new user when "unique email" is enabled and see if I get any issues.
Thanks.
@Rick - I just read over my post and some of it sounds a little harsh, but that's not the way it was intended. I'm just typing faster than my head can keep up. :^)
I appreciate your comments and there's always a chance that I've missed testing something. I will post a response to the unique email issue after I've tested it.
Thanks.
Hey,
Nothing harsh noticed..I think we're just mis-understanding each other. I have the system working - no worries - you asked me what I had changed for VS2010 and it must have been me being stoopid missing the login partial. Second post was just showing you what I got by default using VS 2010 and MVC4 - am past that stage following your instructions.
I can fix the unique email bug if you like - or I'll just wait for you lol...
I can't get email to work for password reset - I have the same account set up in Outlook and it sends using the same details - so I thought it was the authentication issue. I'll play with it some more. Can I suggest a little change to this code:
public virtual ActionResult ForgotPassword(ForgotPasswordViewModel model) You havea try / catch in there and the catch doesn't do anything - so you are not reporting any errors from the email send and just supressing the error. Best Rick
@Rick - if you have a fix for the email bug, you can go ahead and make the changes for now. I'm not sure when I can get to this and I don't want you waiting for me. I'm on a project that has a deadline and can't devote time to this at the moment. I will get to it as soon as I get a break.
When I'm able to test this, whatever changes I make will be reflected in my changelogs.
Thanks.
@Rick - here's some results:
What error do you get with the Unique Email issue? I get nothing.
Love your work!
Still, I don't know how to check user's role(s) within action in cotroller. Because I'm using SecurityGuard, I cannot use the "User" instance and write:
foreach (string rolesForUser in Roles.GetRolesForUser(User.Identity.Name))
{
if (User.IsInRole(rolesForUser))
{
}
}
This is what I got on "User":
An object reference is required for the non-static field, method, or property 'System.Web.Mvc.Controller.User.get'
Also, I tried with:
MembershipUser oCurrentUser = Membership.GetUser();
but there is not method to get user's roles.
Please for help. Thanks!
@Branislav - Hi, I'm not sure what you are trying to do, but these features are already built into SecurityGuard.
There's no need to re-invent the wheel here. I hope this helps.
Hi! Thanks for reply.
I not thought to UI. Let me redefine my question.
I have INDEX action in some controller, and within it, I'am trying to write some code which will check all user's roles. Then, if the user is "admin" my INDEX action will do something, but if the user is "coordinator" too or only the "coordinator" then my index action will do something different.
The question is: How to programmatically (in code) check if the user is "admin" or has some other role?
(Continuation of previous post: Posted By: Branislav On: 8/31/2013 5:45:33 PM)
I'am asking this because the default membership provider is changed to SecurityGuard (web.config) and I lost the ability to use User.IsInRole("admin"). Am I right? If not please let me show how to check user's role(s). Thanks!
@Branislav - SecurityGuard has not changed any functionality that is available in the default Membership providers. You can view the controller code in the SecurityGuard Area to see this. Every function that you need is available.
Regarding your second post, you are not right. SecurityGuard has not replaced the Default Membership providers, unless you have written a custom provider and set that as the default provider, but the default provider should still be System.Web.Providers.DefaultMembershipProvider, System.Web.Providers. All the functions are still there.
Understand that SecurityGuard is just a means of managing the Membership system in the UI, it has not changed any of the default functionality of the Membership system, so you still have all the resources available to you.
To answer your question about getting information on a User, this would be in the realm of the Membership system itself, and has nothing to do with SecurityGuard, but I'll answer it anyway. :^)
You can get access to the user as you normally would:
if (User.IsInRole("admin"))
{
// do something for the admin
}else if(User.IsInRole("coordinator"))
// do something for the coordinator
}else{
// do something for any other role
}
The User Principal is still available in these controllers and you can do whatever you want. If you are writing your own controllers, you need to make sure you have the correct reference to using System.Web.Mvc;, then you have access to that IPrincipal object.
I hope this answers your question.
Yes. Thanks!
My mistake! I called "User" instance from STATIC method I used in controller and it's not possible. Now I fix this (by removind static method property).
Many thanks for your patience.
This is a great tool. I tried installing for a project I am working on but I am getting this error:
An error occurred during the execution of the SQL file 'InstallCommon.sql'. The SQL error number is 5110 and the SqlException message is: The file "\\path.MDF" is on a network path that is not supported for database files.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
Creating the ASPNETDB_bd20aefaba9f4830b2ea2f5e412f04a9 database...
Any ideas why this is happening? Thanks
This is a great tool. I tried installing for a project I am working on but I am getting this error:
An error occurred during the execution of the SQL file 'InstallCommon.sql'. The SQL error number is 5110 and the SqlException message is: The file "\\path.MDF" is on a network path that is not supported for database files.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
Creating the ASPNETDB_bd20aefaba9f4830b2ea2f5e412f04a9 database...
Any ideas why this is happening? Thanks
Could not load type 'SecurityGuard.Services.MembershipService' from assembly 'SecurityGuard, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
Thanks for the wonderful tool.
@prosperva - I'm glad you fixed your problem. The error wasn't a SecurityGuard error anyway.
Cheers.
Sorry I meant the DLL source code.
Thanks
I would like to extend this method: MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, out MembershipCreateStatus status); so that it has extra variables like First Name, Last Name etc. So having the DLL source I can add it and then recompile.
Thanks
@prosperva - hi, did you see my last response? I told you where the source code is, it's in github. Look at the top of this article for the link called "Home Page".
Also, it sounds like to you want to create a profile for a user. I would suggest that you don't modify the CreateUser() method, but instead create either a Profile using the Profiles table found in the Membership database, or create your own User table and simply store user information there.
You really shouldn't modify the CreateUser method because that is meant to simply and easily store information about the user credentials in the database, not profile information about the user.
I hope this helps.
@prosperva - you still can. Just create the new functionality inside the Create action of the controller, after the code that creates the User.
If you extend the Membership provider, then you'll also have to modify the Membership database table. It's up to you, but the other way, is the easier way and more flexible.
Yes I resorted to creating the functionality inside the Create action of the controller; indeed it is much easier.
Thank you very much
Hi,
It has been so fun using your code. I had a small question, does security guard support ldap?
Thanks
Hi,thanks for the module,i want to ask if i want to implement the securityguard is better using blank mvc4 template or internet template?And regarding the connection string,i try to use like following :
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLExpress;Initial Catalog=blog;Integrated Security=TRUE;" providerName="System.Data.SqlClient" />
</connectionStrings>
When i run the application,it doesn't create the blog database,instead it creates ASPNETDB.mdf and putted in App_Data,where should i change it?I'm trying by using the internet template.Thanks
@Tareq - I have not created a version of SecurityGuard that uses the external logins such as Facebook, Google, etc. You should be able to incorporate them into your application by following the default Internet MVC 4 Template that is created in VS 2012. You will have to copy and paste them in and do some testing, but it should work.
If I find a moment, I have put this on my TODO list for SecurityGuard.
@handoyo - in your connectionString, you have the Data Source set as ".\SqlExpress". This will always default to the local .mdf database. If you want to use your SQL Server Standard or above database, you just need to change the data source to point to your database.
As a reminder, SecurityGuard does NOT create a new Membership database for you. You need to have this created first, either through the VS tool, or through my other NuGet Package called MvcInstaller. Then you will be able to point your connection string to your SQL Server database.
Also it doesn't matter which VS template you use, what matters here is the connection string. You are responsible for making sure it's pointing to the correct database.
I hope this helps.
@Michael McGee - if you want to use Claims, then you will most likely have some work to do to integrate that technology into SecurityGuard. I've been thinking about creating a version using Claims, but I haven't had the time.
If you are thinking of integrating Claims into SecurityGuard, you might want to fork my github repository (see the link at the top of the article) and create a new version. I'm always open to collaboration. :^)
Thanks a lot for this mvc plugin, its really great.
Could this plugin also used with the SqlCompact database? As I am very new to the asp.net mvc I have no clue how to setup the Web.config, can you give me a hint, how I should set it up?
best regards
Bernhard
@Bernhard - SecurityGuard can be used whereever the ASP.NET Membership system is installed. You just need to setup your connectionStrings section correctly.
The connectionStrings section should look something like this:
<connectionStrings>
<add name="YourEntityConnectionName" connectionString="Data Source=(LocalDb)\v11.0;AttachDBFilename=|DataDirectory|\YourSqlCompaceDatabase.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
I hope this helps.
Hi,
I'm currently using SecurityGuard in my MVC4 application. I've assume the encryption is using HMACSHA256.
My problem is - I have iOS client and want to validate their user name and password with membership table data.
How do I calculate/generate password based on password salt?
I have done similar thing on asp.net 2.0 with SHA1 algorithm. How do I solve this problem?
Regards,
Dev2709
@dev2709 - The encryption method is the default for ASP.NET. You can use any of those provided to you by the system.
Remember, SecurityGuard is simply a UI sitting on top of the ASP.NET Membership system. I have not recreated any of the underlying technologies to make this work. I simply used what is already there and put a UI on top of it.
What is the problem with your iOS client? The type of client makes no difference, it's all browser-based. When you say validate, are you trying to log them into your application using SecurityGuard? If so, then you can look at the login view and the Login action in the SGAccount controller to see the functionality.
Regarding your password salt question, I also don't understand what you are asking. In SecurityGuard you can create a new user with a password and the framework will do the rest for you, including create the password salt. This is part of the membership system, and not SecurityGuard.
If this doesn't answer your question, can you clarify? Please understand that I can really only answer questions confidently on SecurityGuard, and only generally on the ASP.NET Membership system.
@King Wilder
Thank you for your answer.
My iOS client is native program in C# (by using Xamarin) and I am using webservice to validate the login and password.
My webservice have passwordsalt and password. I have to manually regenerated password in iOS C# and compared against my webservice password. This is not working on MVC4. (It was work on .Net 2.0 membership because of SHA1. Now default hash algorithm is different and I cannot regenerated the same password.
I will try to do with SecurityGuard and SHA1.
Thank you.
Regards,
dev2709
When I go to http://localhost/CostManagementSG/dashboard I get an error
Value cannot be null.
Parameter name: username
I made sure all my users have a user name. one thing I did do was add a field to my users table (businessId). I also went back and updated the DB so everyone had a secret answer (though I am not requiring it).. Any thoughts on this?
Thank you for all you do. This was free so I will never complain. You have already saved me a ton of time.
Is there a secret to getting your areas registered? I get this error when I try to assign roles?
/CostManagementSG/SecurityGuard/Membership/GrantRolesToUser/bademail@mcodemedia.com
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
I am actively look for the solution. But I figured I would ask firs
@Michael McGee - no there is nothing out of the ordinary to use SecurityGuard. You can literally install the NuGet package and it will work. Have you modified anything in SecurityGuard after installation?
Did you say you changed the ASP.NET Membership database schema for your application? That could be the problem.
From the path you show, it seems you have a CostManagementSG application, and then SecurityGuard inside that. Usually SecurityGuard sits off the root. Check and see if the HTML is using absolute paths to the root, instead of relative paths. I'm out right now so I can't check it myself. You should be able to change it and make it work.
@Michael McGee - SecurityGuard is installed via NuGet in an Area in your MVC application, which would place it at the root of your website.
http://www.yourdomain.com/SecurityGuard
Based on your path that you displayed, SecurityGuard is not in this location, that is why you are getting this error. Make sure you have your navigation items pointing to the correct location of SecurityGuard, and that you have not moved the location of SecurityGuard.
I hope this helps.
Looking a little deeper, it might have something to do with my routing.. I am pretty sure my Area is set up correctly. I find if I do this http://localhost/CostManagementSG/SecurityGuard/Membership/GrantRolesToUser?userName=cookie@mcodemedia.com instead of this
http://localhost/CostManagementSG/SecurityGuard/Membership/GrantRolesToUser/cookie@mcodemedia.com it will work. So I will look at my routing. Thank you sir for making me look harder. This is the part I love about coding, the thrill of tracking down a program
@Michael McGee - re: Areas - the Areas folder is never referenced in the URL. So something like:
root/Areas/MyArea/controllers ...
... will be referenced in the Url as ...
http://www.mydomain.com/MyArea ...
... not ...
http://www.mydomain.com/Areas/MyArea
This is standard for MVC routing, nothing unique with SecurityGuard.
So you your application will probably work (if you haven't moved SecurityGuard), as:
http://localhost/SecurityGuard/Membership/etc...
The way the parameter is used is not the reason for your error. It's that the ASP.NET framework cannot find the SecurityGuard controllers with the path you've shown. So you need to have SecurityGuard at the root of your website application.
I hope this helps.
FYI, I build many applications for my clients and I use SecurityGuard will all of them using the default installation. In the custom Admin Dashboard that I create for the website, I just create a navigation link that points to SecurityGuard, and everything works.
<a href="@Url.Action("Index", "Dashboard", new { area = "SecurityGuard" }, null)">Users</a>
I hope this helps.
The easy fix for the routing issue when you have periods in your user name (i.e. email ) is to change the JavaScript to the following when you set the HREF
// Concatenate the existing href value with the username
var newHref = href + "/" + userName + "/"; <--------------- I added forward slash (see line 179 membership index.cshtml)
For the time being I am going to go with this, but I am slightly concerned that we pass the username around as a parm. I would rather pass the userID, so my history on any computer does not have the users email in the url.. Not much of a security concern (or is it?)
@Michael McGee - I'm sorry you are having problems with SecurityGuard. It really does work right out of the box. I'm not sure why you are having issues.
Also, I've created new users using email addresses as usernames without any issues. You shouldn't have to do anything for this to work.
Also, SecurityGuard can be added to a project already built, or a new project, it has no affect on the primary application.
You don't need to be concerned with passing the usernames as either part of the route, or as a parameter, because any application that uses SecurityGuard really should be using SSL to encrypt the traffic. As for the history, unfortunately that's your issue. You have to protect who gets access to your computer. But a user just seeing the history url doesn't mean they can load that page unless they are in the SecurityGuard Role. And if they are, then there is not problem with them seeing it.
Hi,
I have small question. I successfully used MVC Installer when on a DEV server. Then I wanted to deploy the app on PROD server but when I type the address http://prodserver/install, the browser keeps redirecting to the home page. Is there a setting that has to be changed?
Thanks.
@prosperva - you need to add a key back into the appSettings section of the web.config file for deployment. (I'll add this info to the article to be more clear.)
Add this key for deployment:
<add key="AppInstalled" value="false" />
This tells MvcInstaller that it has NOT run yet, or in other words, the database schema and membership has not been installed. Then you will be able to see the /Install view and run it.
Remember to have Write permissions set on your web application during this procedure since MvcInstaller updates the web.config membership sections with values from the Installer.config file. You can revert the permissions back afterward.
Also, FYI, remember to post an MvcInstaller question in the MvcInstaller article, not this SecurityGuard article. :^) This will helps other users if they are looking for answers.
I am new to MVC so I apoligize if this is a silly quesitons. Any help would be greatly appreciated. Thanks!
I installed Security Guard and it was working fine. Then I added an ADO.NET Entity Data Model and I am now getting the following errors:
...Membership' does not contain a definition for 'Provider' - File: MembershipController
...Membership' does not contain a definition for 'Provider' - File: SGAccountController
...Membership' does not contain a definition for 'CreateUser' - File:
...Membership' does not contain a definition for 'GetUser' - File: SGAccountController
...Membership' does not contain a definition for 'Provider' - File: DashboardController
@joe - I have never seen this error before. Can you confirm that the SecurityGuard Area is still installed and all the controllers and views are still there? And the SGAccount controller, is it still there?
If they are, something obviously happened when you installed the Entity Data Model.
One thing you can try is to uninstall and re-install SecurityGuard using the Visual Studio Package Manager. See if that works.
I am trying to use the reset password feature, I am still looking for the solution.. but I figured I would start with you and my provider
does mvcMailer.BaseUrl need to be set to something?
<mailSettings>
<!-- Method#1: Configure smtp server credentials -->
<smtp deliveryMethod="Network" from="support1@profitdreamer.com">
<network enableSsl="true" host="mail.profitdreamer.com" port="465" userName="support1@profitdreamer.com" password="mypassword"/>
</smtp>
</mailSettings>
that info is my outgoing mail server.
@Michael McGee - Hi Michael, no MvcMailer.BaseUrl is not needed and deprecated. I will remove it from future updates.
What you are experiencing is a mailSettings configuration issue, or maybe a firewall issue on your end. This is a SMTP settings issue and not a SecurityGuard issue, FYI, since the mail feature is MvcMailer.
I've encountered this from time to time for a couple reasons:
From localhost, I can use my non-SSL settings and it will work. This way I know that there is nothing wrong with the MvcMailer component or my settings. Then if SSL fails, then I know it's something else, usually one of the items I've listed above.
Give that a try and see if those suggestions help.
I just wanted to update you that I did get my emails working if used port 587 and turned SSL off. I talked to my hosting provider and they told me that .NET does not support enabling SSL that way... Which I am still not sure I believe.. They said I had to use some old COM component or use an older version of System.Web.Dll
They sent me here
http://blogs.msdn.com/b/vikas/archive/2010/07/23/system-net-mail-cannot-send-secured-email-using-smtp-over-ssl-aka-smtps-protocol.aspx
http://stackoverflow.com/questions/1082216/gmail-smtp-via-c-sharp-net-errors-on-all-ports/3845907#3845907
http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx
I know you are a busy man, so I am not asking you to look into it , I am just providing this in case someone else runs into the problem. If I get it all figured out I will post again.. Thank you for all you do! You saved me a month of trying to implement security myself..
@Michael McGee - this is good information. I did not know this. I will add this to the article.
Thanks for the research on this.
FYI, you can get it to work if your SMTP provides the protocol shown in the accompanying articles. I have EnableSsl set to true on most of my clients applications and they are all working on the server. I've just used alternate Ports from 465 and it seems to work. I haven't had to use the older component.
@Michael McGee - Michael, I run my own Microsoft-based hosting business. Most of my customers are mid-sized tech companies. Also, MVC Central is hosted here as well as some customers that are running WordPress and other PHP sites. But if you are running an ASP.NET MVC site, it WILL work! Since I build all my clients web applications in MVC 4, I configured my server to absolutely work with all the latest Microsoft updates and technologies.
I might be a little more expensive that Arvixe, but I provide great customer service. My base hosting plan starts at $9.95/month or $7.96/year if paid annually.
My mail server is on a separate cloud server, and it's run by a company with insane customer service. I've been a partner with them for about 5 years and haven't had any problems.
If you want, you can go month-to-month at first to see if you like it, and if not, you can move. I never prevent any customer from leaving if they want, but many of my customers I've had since the late 1990's. If you are interested email me at info@gizmobeach.com.
Is there any functionality in your project to make them change the password when I have sent them that ugly password? I can implement mine own, but I just wanted to see what you had to say, before I got too deep into it. When they get a new password back like @)**)))[1@, I know they will forget that too, so I was going to set some flag and when they log in with that ugly password, redirect them to the change password function and not let them do anything until they change their password to something they will remember.. Don't do any work, just adivse if you think that is a good idea..
@Michael McGee - no I don't have that functionality in place, because not all applications need or want that out of the box. It would not be very hard to create. You can just make a copy of the ChangePassword view and make the changes to that and point it to a new controller action.
I guess I could add it to a future version and have the Admin choose to implement it or not.
Thanks for responding. Don't do any work. You provided the basic implementation and it is great. We developers need to modify it for our use.. and that is what I am going to do. Gives me a reason to get up in the morning and code..
I want the coding for given concept in ASP.NET
I have one old database for school,now some update occur in the scholl webpage like new persons join and somebody leave from the scholl,we need to compare the Staff details in the given webpage,if it is match it will show in different color
@Bharathi - I'm not sure I understand what you are asking. If you want SecurityGuard for ASP.NET WebForm and not MVC, then it's not available. SecurityGuard was specifically built to be used with ASP.NET MVC, not WebForms. If you want something like this for WebForms, you will need to build it yourself, or look online to see if someone has built something you need.
And regarding your school database, again I'm not sure what you are asking, but it doesn't sound like it relates to SecurityGuard specifically.
Hi King,
Good one and really helpful, Thanks !
Do you support the new simplemembership and mvc4? I had some difficulty getting it working and just wanted to make sure. If possible can you share a sample project with the new simplemembership and mvc 4.
Thanks
Sam
I have installed SecurityGuard on my mVC4 project (VS 2010). When I run my web mvc application I have no problem on local machine but on my deploy server when I click the link that run this istruction ( @Html.ActionLink("Security Guard", "Index", "Dashboard", new { area = "SecurityGuard" }, null) ) I obtain "The page not found Error"; http://www.myserver.it/VirtualDirectory/SecurityGuard
The only difference is that on my deploy server I have one virtual directory
Hi,
Did you take a look at the new Identity system that MS is releasing ? I probably will be using it in a future application and was wondering if you had plans to create some kind of Security Guard for it.
http://www.asp.net/identity
Thanks
thank you very much
sorry i have a question. im begginer in membership. i have 2 roles with same view and i donot know if i have to create 2 seperated view for each role or not.
please help me tanks
Highlight the word on webbrowser
i am using
IHTMLDocument2 doc2=Webbrowser1.Document.DomDocument as IHTMLDocument2;
StringBuilder html=new String Builder(doc2.body.outerHTML);It will show Error IHTMLDocument2 and body
@Bharathi - I'm not sure what you are doing here, it looks like you are creating a browser instance inside a Windows Forms application, or something like that, and this is not what SecurityGuard was meant for. If you have found an error with your code, thanks for pointing this out, but it is not a concern for me.
SecurityGuard is strictly meant to be used in an ASP.NET MVC 3 or 4 application as an Area. I hope this helps.
Hi there. First of all, what a truly awesome implementation of a user management system.
It does what it says and the code is logical enough to manage and adapt to suit my needs. One question though... do you have any examples of utalizing the profile service?
Many thanks and great work
McGeek
Hey King:
This is sweet. I almost have it! but I cant get past Line 146 in the SGAccountController.cs file.
Method not found: 'System.Data.Objects.ObjectContext System.Data.Entity.Infrastructure.IObjectContextAdapter.get_ObjectContext()'.
Im sure this is my error somewhere but any help would be appreciated.
{"Specified method is not supported."}exception in below
membershipService.CreateUser(model.UserName, model.Password, model.Email,
model.SecretQuestion,
model.SecretAnswer,
true, out createStatus);
Hi,
How would you add users but make sure they are not approved?
Thanks
@prosperva - just as a reminder, this is an MvcInstaller question, not a SecurityGuard question... but I'll answer it with a short answer, don't!
MvcInstaller is intended to install your database schema and create your Administrator accounts, and that's all! It's not to be used to create non-Administrator users. Your non-Admin users are to be created the normal way, either where they register themselves using the Register form, or where you create their account for them in SecurityGuard.
I hope this answers your question.
Hello
After login as a "superadmin", when I click on the "Security Guard" action link, I get following runtime error.
System.InvalidCastException: [A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from 'System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_1.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'. Type B originates from 'System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'.
@wafeeq - sorry, I've never seen this exception. It looks like there's a difference in the version of Razor in your application.
What's the version of the MVC application that you created? And what's the version of SecurityGuard that you installed?
Thanks King for Replying,
I was already working on an application and have developed some features. Now I wanted to make role management and forms authentication.
my application is asp.net MVC4. Version of SecurityGuard 1.0.51.580 was the latest one.
MVCInstaller Version is 2.0.2.0
Hello King,
No, not yet I am still in problem. There is nobody talking about converting from razor v2 to v1 or ever converting from mvc4 to mvc3. Do you have any Idea to switch back? or just chaging the razor version?
Hello King,
No, not yet I am still in problem. There is nobody talking about converting from razor v2 to v1 or ever converting from mvc4 to mvc3. Do you have any Idea to switch back? or just chaging the razor version?
Hi,
I ve installed the package, in my ASP .Net MVC Application, but when i try to access to the http://myhost/SecurityGuard/Dashboard/Index
this error is caught by the server :
[A]System.Web.WebPages.Razor.Configuration.HostSection ne peut pas être converti en [B]System.Web.WebPages.Razor.Configuration.HostSection. Le type A provient de 'System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' dans le contexte 'Default' à l'emplacement 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'. Le type B provient de 'System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' dans le contexte 'Default' à l'emplacement 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\b7cbfd8b\16c09dde\assembly\dl3\33cc6da3\99bb9f81_f544cf01\System.Web.WebPages.Razor.dll'.
Which mean that the type A could not be converted to type B.
Any idea?
Help please.
In VS 2013 I install securityguard while click SecurityGuard the following error is accour
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.Line 4: <configSections> Line 5: <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> Line 6: <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> Line 7: <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> Line 8: </sectionGroup>
MVC 5 Fix
To All who are installing SecurityGuard.MVC4 in an MVC 5 application, I am aware of the issue and I will create a new version shortly.
In the meantime you can easily fix this by going into the /Areas/SecurityGuard/Views/web.config and modifying the three section group elements of the config file and change the version from 2.0.0.0 to 3.0.0.0. This will fix the issue until I make a new version.
I apologize for the inconvenience.
Hi
Should I be able to get this to work with Oracle ?
Any tips appreciated
thanks
Glenn
@glenn, it has not been tested against Oracle. It most likely won't work because it uses the Membership providers that, I think are specific to SQL Server.
Sorry.
@glenn, it has not been tested against Oracle. It most likely won't work because it uses the Membership providers that, I think are specific to SQL Server.
Sorry.
Hey King Wilder!
Im want ask something.
Im using SECURITY GUARD for my website. Im want login use facebook and after save account facebook more and more.
I can't do it.
Guid me!
Thanks you very much!
Hi King!
Help me solve it!
@hoang nguyen - at the moment, this version of SecurityGuard goes not contain this feature out of the box. But you can add this feature yourself. Just take the code from the Visual Studio template that uses the Social Media components for authentication, and then integrate it into your application.
You have the source code for both SecurityGuard and the Social Media authentication functions, so you should be able to integrate them together.
I hope this helps.
Hi King!
I using social media default off membership. I shouldn't be able to integrate them together.
How can i add this feature? Could you help me.
OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
It error.
And Password not empty when create new account.
Sorry you, My English very bad
Are you understand, you aren't
I just need add login use account facebook and after login save account into database.
Could you help me. just help how is it do? -_-
I can login with account facebook but i can't save new account facebook into my database.
different between table User and UserProfile. and membership and Security Guard.
ali
@joe - it's hard for me to diagnose this with what you have told me, but have you looked at the articles and videos on how it's used? There aren't any used methods in SecurityGuard with the System.NotImplementedException exception.
Let me know.
Method:
public DashboardController()
{
this.roleService = new RoleService(Roles.Provider);
this.membershipService = new MembershipService(Membership.Provider);
}
As far as I can tell, it installed properly.
If I try to navigate to http://localhost:[port]/SecurityGuard it takes me to the above method and then to the login screen.
I am getting the NotImplementedException in the SecurityGuard Area in the Dashboard Controller when I hover over roleService.
I don't have role records in the Roles table. Could this be causing it?
@joe - sorry for the late reply, but I still don't have any quick answers. I assume you DO have roleManager section in your web.config set to "enabled=true", correct? And all the type attributes are: type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", correct?
If you already have this part configured, I would just say that you should uninstall the package, and then reinstall it and see if it works then. It won't affect any part of your code or database, it simply removes all references to the SecurityGuard installation and then reinstalls it.
Try that.
Thank you
Claudio
@Claudio Pérez - this behavior is specific to the ASP.NET Membership system, not SecurityGuard. When you add a machine key to the web.config file, the Membership system will use it to encrypt credentials. So if you already have some credentials created without the key, then you cannot add the key after that because the encryption will be different.
If you want to use a machine key for encryption/decryption, you need to add it before creating any accounts.
I hope this helps.
I use your security Guard on an existing project
I have create user With dot (.) in username like "xxx.yyyy" . And then when I want to update user or give role this user i have thise Error,
File or directory not found
localhost:59000/SecurityGuard/Membership/Update/xxx.yyyy
@ King Wilder, how did you fix the issue with (.) dot notation? I need help. Thank you.
@david - this issue with SecurityGuard was fixed in the latest Mvc4 and Mvc5 releases.
What issue are you having? Creating a username with a dot? Editing?
I installer Security Guard MVC4 couple of days ago using NuGet (Install-Package SecurityGuard.MVC4 ), so I guess I have the latest update and still having issues with usernames with dot in them.
Whenever I enter a username with dot and press create it gives me 404 error. But the user is created, and I can see the user in Manage users page.
While the following links result in 404 error:
/SecurityGuard/Membership/GrantRolesToUser/king.wilder
/SecurityGuard/Membership/Update/king.wilder
i am using visual stutio 2013 in mvc5 application.
The entry 'MyCoolEntities' has already been added.
@britto - sorry this is so late, I didn't even know you had posted this comment. Just to let you know, this is an MvcInstaller issue and not a SecurityGuard issue, but I'll answer it here. This is a bug that I'm trying to find time to fix, but you can make it work by removing the connection string prior to opening the Install page. MvcInstaller updates your web.config/connectionString setting for you based on your Installer.config configuration.
You usually get this error when you are installing MvcInstaller into an appliation that you've already been working on, one that has a working connection string set, etc. By removing the connection string element, saving the web.config file, and then refreshing the /Install page, it should work.
On some versions you may get one other error, and this is when it tries to update the membership providers that are already set. So until I can get time to fix this bug, this workaround should fix it and allow you to see the Install page to install your app.
When both of these are removed, you should be able to see the Install page and install your application. I hope this helps. (You probably already figured out a workaround by now, sorry)
Hi King, Thanks for your answer, but, i need to store booth authentication and application data in the same database, how to perform that ? i have already created a database under sql server 2014 and the connectionstring is registered in the web.config file.
Regards.
@Medessad - if you are using Microsoft Identity, as I mentioned before, you can't use SecurityGuard. If you want to use SecurityGuard using the security providers that it comes with, then you can do what you want.
If you use MvcInstaller to install the ASP.NET Membership system into your database, along with your application's schema, then SecurityGuard just sits on top of that to give you a nice interface for managing your membership system. Read the articles and watch the videos on MvcInstaller for more information.
But again, Identity is not supported with SecurityGuard, at this time.
Hi ...
Have the error when try to Register new user. Trying Uninstall/Install the package the error remains, but Login and Log Off works.
Can you please help?
-------------------------------------------------------
http://localhost:51561/SGAccount/Register
------------------------------------------------------
Server Error in '/' Application.
Specified method is not supported.
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 144: // Attempt to register the user Line 145: MembershipCreateStatus createStatus; Line 146: membershipService.CreateUser(model.UserName, model.Password, model.Email, model.SecretQuestion, model.SecretAnswer, true, out createStatus); Line 147: Line 148: if (createStatus == MembershipCreateStatus.Success)
and same have on
http://localhost:51561/Dashboard
Server Error in '/' Application.
Specified method is not supported.
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 31: int totalRecords; Line 32: Line 33: membershipService.GetAllUsers(0, 20, out totalRecords); Line 34: viewModel.TotalUserCount = totalRecords.ToString(); Line 35: viewModel.TotalUsersOnlineCount = membershipService.GetNumberOfUsersOnline().ToString();
@app - the error message shows that it is trying to use the SimpleMembership provider. SecurityGuard doesn't use this provider. It looks like you are using WebMatrix, is that correct? If so, I have not tested this with WebMatrix, but it looks like the membership providers are clashing. For this to work you will have to remove the SimpleMembership providers.
Actually I can't really tell you to do that because I don't know what the result will be. My suggestion is to use Visual Studio if you can and create the application with the standard Web templates. My lack of knowledge about WebMatrix won't help you in this situation. Sorry.
Thank You!!! for your quick answer...
Really my fault I have SimpleMembership and your code for Membership.
You specify this on top, need read all carefully :)
Pre-requisites:Hi,
I just ran into this issue:
0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'addBack'
Jquery version 1.8 or above has the addback?
I get an error with the script and then if I continue all is well. Using Visual Studio 2013
Thanks
Unhandled exception at line 19, column 2746 in http://localhost:16314/Scripts/jquery.validate.unobtrusive.min.js
0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'addBack'
When in the Dashboard and using
Creat Userhttp://localhost:16314/SecurityGuard/Membership/CreateUser
Hope this helps, this seems to be the only issue I have the work around I use is to register User and not use the Create User in the Dashboard.
Thanks
David
Hi,
Thanks for the update, I tried updating the jQuery version to 1.8 but ran into a lot of problems. I will wait for the update as it works with my work around. My create user if I ignore the script error I can in fact create a user.
Thanks
I have a customer registration controller I am creating.
when I get to (membershipService.CreateUser(model.EmailAddress, model.Password, model.EmailAddress, null, null, true, out createStatus);) then I get
Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.
public virtual ActionResult Index(RegistrationModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
if (ModelState.IsValid)
{
var createStatus = new MembershipCreateStatus();
membershipService.CreateUser(model.EmailAddress, model.Password, model.EmailAddress, null, null, true, out createStatus);
// MembershipCreateStatus createStatus = membershipService.CreateUser(model.EmailAddress, model.Password, model.EmailAddress );
//RVmodel.UserName = model.EmailAddress;
if (createStatus == MembershipCreateStatus.Success)
{
formsAuthenticationService.SetAuthCookie(model.EmailAddress, false /* createPersistentCookie */);
RoleService.AddUserToRole(model.EmailAddress, "Administrator");
RoleService.AddUserToRole(model.EmailAddress, "SecurityGuard");
Hi
any reason that I should be aware of why my app works locally but will not register a user when deployed to azure?
Thanks
Hi
I'm getting an error when trying to delete a user, invlaid table Profiles - any clues why this is happening?
thanks
@darretking - I apologize for not responding sooner, I didn't get a notice that you posted this comment. You have probably figured it out by now, but if not, can you figure out where the null reference is coming from?
BTW, you really don't have to create a custom Registration form, you can simply modify the existing Registration controller action to fit your needs. I've done that on many occasions.
Also, I've used it in Azure successfully, although you should have the Nuget package installed locally before publishing to Azure. And you need to make sure the connection string is correct in case it's different from your application database connection.
Hi
Thanks - v1.0.53.580
I put a sql profiler on the db but didnt see any statements for the delet, so not sure it's even getting that far?
The error is: Invalid object name 'dbo.Profiles'.
It's an inherited app, database schema as per below:
Thanks for your help, appreciated
@goolag - this will not work for your database. The Membership system already has an "Applications", and "Memberships" table, and so does your database. So you have a few choices:
I would go with the first option, creating a separate database for the membership system.
Good luck.
Hello ,
I am using SecurityGuard.MVC4(1.0.10) in one of my application for memerhsip.I want to chnage "connection string" at runtime for membership and roles .how do i do that?
Waiting for your response asap.
Thanks,
Pallav Joshi