ASP.NET Profile save overwritten by old values - c#

I am using the Profile feature of ASP.NET in a website. Updating a profile is working weirdly! A user can't update his/her own profile, neither the web site user nor the administrator, but, the administrator is able to update profiles of other users.
In the backend, after Profile's save() is called, SQL Server traces show that aspnet_Profile_SetProperties stored procedure is called twice. First, with new values, then, with old values. The second execution is done after page unload. My code has nothing to do with transactions.
Why is it working so weirdly?
Could there be an issue with aspnet_regsql's installation as I have installed uninstalled and again installed it!?
Code
web.config
<authentication mode="Forms">
<forms name="FormsAuthentication" loginUrl="~/Login.aspx" defaultUrl="~/Login.aspx" timeout="20"/>
</authentication>
<membership defaultProvider="CustSqlMembershipProvider">
<providers>
<add connectionStringName="connString" applicationName="/space_online" minRequiredPasswordLength="5" minRequiredNonalphanumericCharacters="0" name="CustSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider"/>
</providers>
</membership>
<roleManager enabled="true" defaultProvider="CustSqlRoleProvider">
<providers>
<add connectionStringName="connString" applicationName="/space_online" name="CustSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"/>
</providers>
</roleManager>
<anonymousIdentification cookieless="AutoDetect" enabled="true"/>
<profile defaultProvider="CustSqlProfileProvider" enabled="true">
<providers>
<add name="CustSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="connString" applicationName="/space_online"/>
</providers>
<properties>
<add name="FirstName" type="System.String"/>
<add name="LastName" type="System.String"/>
<add name="Email" type="System.String"/>
<group name="Address">
<add name="Street" type="System.String"/>
<add name="City" type="System.String"/>
<add name="PostalCode" type="System.String"/>
</group>
<group name="Contact">
<add name="Phone" type="System.String"/>
<add name="Mobile" type="System.String"/>
<add name="Fax" type="System.String"/>
</group>
<add name="ShoppingCart" type="psb.website.BLL.Store.ShoppingCart" serializeAs="Binary" allowAnonymous="true"/>
</properties>
</profile>
Code behind
private void UpdateProfile(ProfileCommon myprofile)
{
myprofile.FirstName = tbFirstName.Text.Trim();
myprofile.LastName = tbLastName.Text.Trim();
myprofile.Email = tbEmail.Text.Trim();
myprofile.Address.Street = tbStreetPhysical.Text.Trim();
myprofile.Address.City = tbCity.Text.Trim();
myprofile.Address.PostalCode = tbPostalCode.Text.Trim();
myprofile.Contact.Phone = tbPhone1.Text.Trim();
myprofile.Contact.Mobile = tbMobile.Text.Trim();
myprofile.Save();
}
private ProfileCommon GetProfile()
{
ProfileCommon profile = this.Profile;
if (Request.QueryString["UserName"] != null && HttpContext.Current.User.IsInRole("Admin"))
profile = this.Profile.GetProfile(Request.QueryString["UserName"].ToString());
else
profile = this.Profile.GetProfile(HttpContext.Current.User.Identity.Name);
return profile;
}
protected void tbUpdateProfile_Click(object sender, ImageClickEventArgs e)
{
UpdateProfile(GetProfile());
}

The profile is by default automatically saved at the end of the execution of an ASP.NET page, see the profile Element (ASP.NET Settings Schema) documentation on this. This explains the second "mysterious" save that you observe.
You can try to change automaticSaveEnabled to false.

all the transactions must be done before page unload.
if page is unloaded then its all function calls will also be removed or stopped in midway.

Access to ProfileCommon should be done through HttpContext.Current.Profile as that is a reference to the current user's profile (logged in or anonymous) and you don't need to explicitly call Save. Try this:
private void UpdateProfile()
{
var myprofile = HttpContext.Current.Profile as ProfileCommon;
if (profile == null) {
throw new InvalidOperationException("HttpContext.Current.Profile is not of type ProfileCommon for some reason!");
}
myprofile.FirstName = tbFirstName.Text.Trim();
myprofile.LastName = tbLastName.Text.Trim();
myprofile.Email = tbEmail.Text.Trim();
myprofile.Address.Street = tbStreetPhysical.Text.Trim();
myprofile.Address.City = tbCity.Text.Trim();
myprofile.Address.PostalCode = tbPostalCode.Text.Trim();
myprofile.Contact.Phone = tbPhone1.Text.Trim();
myprofile.Contact.Mobile = tbMobile.Text.Trim();
}

You may need to clear the default provider in your web.config.
Like this:
<profile defaultProvider="CustSqlProfileProvider" enabled="true">
<providers>
<clear /><!-- here -->
<add name="CustSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="connString" applicationName="/space_online"/>
</providers>
<properties>
<...>
</properties>
</profile>
Here is a good explanation for this:
Removing existing profile providers
And here is another good site:
http://odetocode.com/articles/440.aspx

Related

Forms Auth: Where’s my auth cookie gone?

Where’s my auth cookie gone?
When redirecting from my SSO to a client application, the .ASPXAUTH cookie is lost but only if the two sites are not on the same server.
In Fiddler, I can see the cookie being set by the SSO to the Response, in the correct cookie path for the client app. Upon redirecting however, I see that the request does not bear the cookie.
Response after logging into SSO:
Request back to client application:
Relevant sections of the Login apps web.config:
<machineKey compatibilityMode="Framework20SP2"
decryption="AES"
decryptionKey="<a valid RSA key>"
validation="SHA1"
validationKey="<a valid HMACSHA256 hash>"
/>
<!-- "SHA1" actually implements HMACSHA256, but for one reason or another, we can't specify it explicitly. -->
<authentication mode="Forms">
<forms loginUrl="Index"
cookieless="UseCookies"
requireSSL="false"
name=".ASPXAUTH"
path="/path/to/SSO-Virtual-Directory/"
slidingExpiration="true"
timeout="20"
enableCrossAppRedirects="true"
protection="All"
ticketCompatibilityMode="Framework20"
/>
<!-- set cookie path relative to virtual path of the application in IIS. See Application -> Advanced Settings to see the virtual path.
Cookie Paths, Domains, and Names are all CASE SENSITIVE!!!!!
Be sure to check the virtual path, as it doesn't update when you rename path tokens to change case. you will have to recreate the application to update the virtualpath-->
</authentication>
<!--SSOConfig Providers-->
<membership defaultProvider="SqlMembershipProvider" >
<providers>
<clear />
<add name="ADMembershipProvider"
connectionStringName="ADConnectionString"
attributeMapUsername="sAMAccountName"
enableSearchMethods="false"
connectionUsername="<a valid domain username"
connectionPassword="<a valid password>"
type="System.Web.Security.ActiveDirectoryMembershipProvider"
/>
<!-- do not set applicationName= .-->
<add name="SqlMembershipProvider"
connectionStringName="SqlConnectionString"
applicationName="SSO"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="true"
passwordFormat="Hashed"
minRequiredNonalphanumericCharacters="0"
type="System.Web.Security.SqlMembershipProvider"
/>
<!-- for some messed up reason applicationName is required.-->
</providers>
</membership>
<roleManager defaultProvider="SqlRoleProvider"
enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPROLES"
cookieTimeout="30"
cookiePath="/path/to/Virtual-Directory/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All"
>
<!--set cookie path relative to virtual path of the application in IIS. See Application -> Advanced Settings to see the virtual path. eg: /secure/sso/CentralLogin/ on Exodus.
Cookie Paths, Domains, and Names are all CASE SENSITIVE!!!!!
Be sure to check the virtual path, as it doesn't update when you rename path tokens to change case. you will have to recreate the application to update the virtualpath-->
<providers>
<clear />
<add name="SqlRoleProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="SqlConnectionString"
applicationName="SSO"
/>
<!-- set ApplicationName-->
</providers>
</roleManager>
Client Web.config:
<machineKey compatibilityMode="Framework20SP2"
decryptionKey="<The same RSA key>"
validation="SHA1"
validationKey="<The same HMACSHA256 hash>"
/>
<authentication mode="Forms" >
<forms loginUrl="~/login/Index"
name=".ASPXAUTH"
path="/Payment/"
requireSSL="false"
slidingExpiration="true"
timeout="20"
cookieless="UseCookies"
enableCrossAppRedirects="true"
protection="All"
ticketCompatibilityMode="Framework20"
/>
</authentication>
<membership defaultProvider="SqlMembershipProvider" >
<providers>
<clear />
<add name="ADMembershipProvider"
connectionStringName="ADConnectionString"
attributeMapUsername="sAMAccountName"
enableSearchMethods="true"
connectionUsername="<a valid domain username"
connectionPassword="<a valid password>"
type="System.Web.Security.ActiveDirectoryMembershipProvider"
/>
<add name="SqlMembershipProvider"
connectionStringName="SqlSSOConnection"
applicationName="SSO"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="true"
passwordFormat="Hashed"
minRequiredNonalphanumericCharacters="0"
type="System.Web.Security.SqlMembershipProvider"
/>
</providers>
</membership>
<roleManager defaultProvider="SqlRoleProvider"
enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPROLES"
cookieTimeout="30"
cookiePath="/Payment/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All"
>
<providers>
<clear />
<add name="SqlRoleProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="SqlSSOConnection"
applicationName="SSO"
/>
</providers>
</roleManager>
Both sites are MVC5 on .Net 4.5.2.
Does anyone have any ideas as to whats going wrong, and what I can do about it?
So as we seems to found out in comments, the problem is SSO and client reside on different domains\ips and so cookie set for SSO will not be passed to client by browser. There are different ways to solve this, but they require change of how your general SSO process works.
As I understand you only have problem with that in development environment, not on production. If so, suppose your SSO is on 10.0.0.1 and your client is on 127.0.0.1. Then map client.yoursite.local domain (in your corporate DNS or just in /etc/hosts file) to 127.0.0.1 and yoursite.local to 10.0.0.1, and use domain names instead of raw ip addresses. Then in SSO set cookie with domain of ".yoursite.local". This then should be delivered correctly to your client application, and will not require significant changes to how your SSO process works.

MVC 4 Membership Can't login

I've created an MVC 4 app and for the first time I am trying to use membership.
I have a sql database where I have created the membership tables and using "ASP.NET Configuration" I have selected my providers, added roles and a user.
When I try to login using the login page, I get the error;
To call this method, the "Membership.Provider" property must be an
instance of "ExtendedMembershipProvider".
I am not using azure nor am i using NuGet.
My config file looks like;
<membership defaultProvider="SqlMembershipProvider">
<providers>
<add connectionStringName="ApplicationServices" name="SqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="SqlRoleProvider">
<providers>
<add connectionStringName="ApplicationServices" name="SqlRoleProvider"
type="System.Web.Security.SqlRoleProvider" />
</providers>
</roleManager>
That's all that was added for me.
My account controller has the following attribute but removing it makes no difference.
[InitializeSimpleMembership]
and it fails on this line;
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
What do I need to do to be able to log users in?
You set SqlMembershipProvider in config but trying to use SimpleMembershipProvider
Pick one and cofigure your app accordingly.
If you set up db against SimpleMembersip (most frequently one table with UserId, Username and other fields), then change your config as follows and make sure InitializeSimpleMembershipFilter looks for userId, username fields as they are set up in your table:
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear/>
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
<roleManager defaultProvider=“SimpleRoleProvider“>
<providers>
<add name=“SimpleRoleProvider“ type=“WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData“/>
</providers>
</roleManager>
Otherwise, to set up SqlMembershipProvider you may refer to the bottom of this page: http://msdn.microsoft.com/en-us/library/system.web.security.sqlmembershipprovider.aspx

IIS7 Session loses its values

I've implemented a challenge-response scheme as an Ajax handler.
For some reason it stopped working after working fine for a couple months.
Investigating the issue showed that Context.Session[KEY] had lost its value between the challenge and the response calls.
I put Session_Start and Session_End (and a few other) methods in Global.asax.cs with some logging there and I see a new Session_Start event being fired with the same session ID and there was no Session_End event
Question is: why does IIS lose the session values?
Update: I tried switching to SQLServer sessions but there was no change in behavior. On rare occasions sessions work as intended, not sure why. I tried all "session losing variables" troubleshooting guides I could find to no effect
UPDATE 2: I narrowed down the issue to a missing session cookie, but modifying my.browsers config didn't resolve the issue after several attempts. When I call the ajax handler from a browser the session cookie "ASP.NetSessionId" shows up as expected. I changed the cookie name in IIS settings for both the site and the server to "SessionId" but I kept seeing ASP.NET, even after restarting the server. I would still like to give the bounty to someone who has an idea what's going on. In the meanwhile I worked around this problem by setting a session cookie in code.
Pseudo code for Login.ashx:
string login = GetParameter("login", context);
string passhash = GetParameter("pass", context);
string challenge = "" + Context.Session["CHALLENGE"];
if (!string.IsNullOrEmpty(challenge))
{
// this is the 'response' part
string challengeResponse = Crypto.GetChallengeResponse(Challenge, UserFromDB.PassHash);
if (challengeResponse == passhash)
{
// Great success, challenge matches the response
Log.I("Success");
return "SUCCESS";
}
else
{
Log.W("Failed to respond");
return "FAILED TO RESPOND";
}
}
else
{
// if passed login or session-stored challenge are empty - issue a new challenge
challenge = "Challenge: "+ Crypto.GetRandomToken();
Context.Session["CHALLENGE"] = challenge;
Log.I("Sent Challenge"); // this is what's in the log below
return challenge;
}
Here's the log, Session started appears with each call, Session.Keys.Count stays 0 even though Session["CHALLENGE"] should have been set:
// This is the challenge request:
[] **Session started**: sr4m4o11tckwc21kjryxp22i Keys: 0 AppDomain: /LM/W3SVC/1/ROOT-4-130081332618313933 #44
[] Processing: <sv> **MYWEBSITE/ajax/Login.ashx** SID=sr4m4o11tckwc21kjryxp22i
[] Sent Challenge #Login.ashx.cs-80
// this is the response, note that there's another Session started with the same id
// and the session didn't keep the value ["CHALLENGE"], there are no session-end events either
[] **Session started**: sr4m4o11tckwc21kjryxp22i Keys: 0 AppDomain: /LM/W3SVC/1/ROOT-4-130081332625333945 #93
[] Processing: <sv> **MYWEBSITE/ajax/Login.ashx?login=MYLOGIN&pass=RuhQr1vjKg_CDFw3JoSYTsiW0V0L9K6k6==**
[] Sent Challenge #Login.ashx.cs-80 >Session: sr4m4o11tckwc21kjryxp22i
web config, sanitized
<?xml version="1.0" encoding="utf-8"?>
<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=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="IncludeStackTraceInErrors" value="false" />
</appSettings>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
<add name="MYConnection" connectionString="metadata=res://*…. and a bunch of other stuff that works" providerName="System.Data.EntityClient" />
</connectionStrings>
<system.web>
<compilation targetFramework="4.5">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages controlRenderingCompatibilityVersion="4.0" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>
What is the default value for Idle Time-out ? If the app pool times out your session goes bye bye
See Application Pool (Advanced Settings) -> Idle Time-out
I think it defaults to five minutes.
See this link for advice on setting the idle timeout
You could also experience your issue if your running as a webgarden when it's not needed; look at Maximum Worker Processes, try setting it to 1 and retest
I can see you are using handler for that purpose which would always return null.
You need to implement IReadOnlySessionState.
Check out http://www.hanselman.com/blog/GettingSessionStateInHttpHandlersASHXFiles.aspx
Add IRequiresSessionState to your handler implimentation
ex
public class handler_name:IHttpHandler, IRequiresSessionState

Microsoft Media Platform + Forms Authentification

Forms Authentication does not work. Auth cookies are not sent to server when SMF attempts to get access to *.ism/Manifest files on a server that requires specific user roles.
What i do:
1. Create new Silverlight Smooth Streaming template with supporting RIA WCF.
2. Configure web.config :
<connectionStrings>
<add name="ApplicationServices" connectionString="Data Source=[SERVER];Initial Catalog=[CATALOG];User ID=[USER];Pwd=[PASSWORD];" providerName="System.Data.SqlClient" />
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
<properties>
<add name="Gender" />
<add name="Birthday" />
<add name="AvatarPath" />
</properties>
</profile>
<roleManager enabled="true">
<providers>
<clear />
<add connectionStringName="ApplicationServices" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" />
<add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
</providers>
</roleManager>
Add Authentification Service and correct User class (add 3 props).
On client side add this to app.xaml.cs:
public App()
{
//Default things...
InitializeWebContext();
}
private void InitializeWebContext()
{
WebContext webContext = new WebContext();
var fa = new FormsAuthentication();
var ac = new AuthenticationDomainService1();
fa.DomainContext = ac;
fa.Login(new LoginParameters("user", "password"), (y) =>
{
if (!y.HasError)
{
this.RootVisual = new MainPage();
}
}, null);
webContext.Authentication = fa;
ApplicationLifetimeObjects.Add(webContext);
Resources.Add("WebContext", WebContext.Current);
}
Access is restricted by web.config file in target directory:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<authorization>
<allow roles="Role_name" />
<deny users="*" />
</authorization>
</system.web>
</configuration>
User exists in this role.
When I use the default video that's specified in Xaml (Big Bunny) - everything is fine. But when I change mediasource to a path to s restricted zone on my server I get an access error.
On the client side, I get user credentials succesfully.
Fiddler shows next thing:
When I try access to another resctricted methods ([RequiresAuthentication]) on RIA WCF, client send Auth cookies, but when SMFPlayer try access to media source, that cookie wasn`t sent.
What have I missed?
I found some workaround:
If you transfer the stream files into a subdirectory, and restrict access to it (instead of a directory with "ism" files). Manifest will be issued to anonymous users, but the data streams is only for registered (when player try touch data stream it sucessfully attach auth cookies).

MVC 3 Application With ASP.Net Membership Provider Login Issue

I appear to have an unusual problem -
I've used the aspnet membership provider before without any issues but this just isn't working out for me.
I've added the schema to my database on sql server through the wizard. To configure the application for first use I run a script that fills the database with some sample accounts, roles, and other information.
After I run this script, I can login in within the application with the newly created usernames, use the features, etc. However after a while, or if I close the development server from the task bar, and then launch the application again and try to login - it won't validate the user. It fails the second IF statement to Validate the user and password below.
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
If I check the database, the user is clearly there, however the incorrect password attempts field is still at 0, which might indicate that the application is not even recognising these as users. Also, If I check the website configuration (VS2010 -> Project -> ASP.NET Configuration) it shows that there are 0 existing users.
If I re-run the application, and run the setup script again, I can log in like before, however after again if I relaunch and try to login again I get the familiar incorrect password/username screen. Sometimes it happens on a different port number however sometimes the port numbers are the same and it still happens.
Here is the setup script:
protected void btnSetUp_Click(object sender, EventArgs e)
{
ModelContainer ctn = new ModelContainer();
Membership.ApplicationName = "MyApp";
Roles.ApplicationName = "MyApp";
if (!Roles.RoleExists("Administrator"))
Roles.CreateRole("Administrator");
if (!Roles.RoleExists("User"))
Roles.CreateRole("User");
// Delete all existing users.
//
foreach (MembershipUser user in Membership.GetAllUsers())
{
Membership.DeleteUser(user.UserName, true);
}
// Create the master admin account.
//
if (Membership.GetUser("admin#MyApp.com") == null)
{
MembershipUser adminUser = Membership.CreateUser("admin#MyApp.com", "admin123");
Roles.AddUserToRole("admin#MyApp.com", "Administrator");
}
CreateUser(ctn, "User#MyApp.com", "Joe Bloggs", "Employee", 1);
ctn.SaveChanges();
}
private void CreateUser(ModelContainer ctn, string emailAddress, string Name, string type, int baseShop)
{
// Create the User.
//
if (Membership.GetUser(emailAddress) == null)
{
MembershipUser adminUser = Membership.CreateUser(emailAddress, "admin123");
Roles.AddUserToRole(emailAddress, "User");
User u = new User
{
Name = Name,
Type = type,
BaseShop = baseShop,
Login = new Guid(adminUser.ProviderUserKey.ToString())
};
ctn.AddToUsers(u);
}
}
My Web.Config is more or less the default so I'm not sure if it's anything from that but there it is anyway:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<connectionStrings>
<add name="ModelContainer" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="Data Source=localhost;Initial Catalog=MyApp;User ID=**;Password=**;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
<add name="ApplicationServices" connectionString="data source=localhost;initial catalog=MyApp;user id=**;password=**;" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="MyApp" />
</providers>
</profile>
<roleManager enabled="true">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="MyApp" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="MyApp" />
</providers>
</roleManager>
<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>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Finding it very hard to be more descriptive of the issue but it's just puzzling. Is there a step I've missed in using the asp.net membership provider? Has anyone else come across this before?
Would be very grateful for any advice.
I think the problem is because you are using your own custom app in the setup code
Membership.ApplicationName = "MyApp";
Roles.ApplicationName = "MyApp";
but your web.config is using the default name
applicationName="/"

Categories

Resources