Membership.CreateUser keeps throwing 'InvalidAnswer' - asp.net

I've been trying to use the CreateUser method to add users to my database. One thing I want is that password questions and answers aren't required, and so I have this in my Web.config:
membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider"
connectionStringName="CBCFXConnString"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="8"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="CBCFX"/>
as you can see, I've set the requiresQuestionAndAnswer to false. This setting has been in my configuration ever since I started programming, and I am just dumbfounded as to why that InvalidAnswer persists when I try adding a user with this line:
fxSMP.CreateUser(userName, passWord, eMail, null, null, true, null, out status);
I've even tried passing empty strings to the question and answer arguments:
string pwQuestion = "";
string pwAnswer = "";
fxSMP.CreateUser(userName, passWord, eMail, pwQuestion, pwAnswer, true, null, out status);
but still nothing. What can I do to make this work?
EDIT: I've gone around the internet some more, and there appears to be an overload method wherein you could only input a UserName, Password and Email. Why does this overload not seem to be available in my instance of SqlMembershipProvider?

In your question I can't see how you are declaring the membership element in the web.config file but make sure you set the defaultProvider attribute...just in case. Also, I'd suggest you to use a different overload of the CreateUser method...
System.Web.Security.Membership.CreateUser(string username, string password, string email)
Edit
Now, since you are using the SqlMembershipProvider this overload will not be available. Why? First, because you are NOT supposed to be calling this method directly on your client code. You should rather use the Membership class. If you set the defaultProvider of the membership element in the web.config file and set the requiresQuestionAndAnswer to false then you shouldn't have any issues whatsoever.
By the way, check out this MSDN Documentation

Related

PasswordReset() throws exception - passwordAnswer?

I have an app that I'm trying to implement the following, but can't seem to figure out how:
User signs up, but the system creates its own temporary password for them
Admin approves user and as part of that approval, the user gets sent a temporary username/password.
The problem is that I can't set the MembershipProvider to enable password retrieval as that seems to disable certficate authentication. I do have passwordReset enabled, but when I try to use it in step 2 (trying to create a new password so I can have it in plaintext to email it to the user), it throws an error:
General Error: System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: passwordAnswer
Is there any way around this?
Here's a code snippet of the relevant code:
MembershipUser mu = Membership.GetUser(Session["UserId"], false);
string password = mu.ResetPassword();
The password is null because nothing got entered. In your code, just use an if:
if (passwordAnswer==null){
//do stuff here
}
While you can write anything there, I recommend, maybe:
if (passwordAnswer==null){
passwordAnswer=" ";//just a space
}
If you want it to be a generated password, research on generating random alphanumeric strings.
I was able to circumvent this issue by adding requiresQuestionAndAnswer="false" to the membership provider in my web.config:
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
requiresUniqueEmail="true"
connectionStringName="DB"
applicationName="Acme"
maxInvalidPasswordAttempts="3"
requiresQuestionAndAnswer="false"
enablePasswordReset="true"
minRequiredPasswordLength="15"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="3"
passwordFormat="Hashed" />
</providers>
</membership>

Is correct this code in web.config for set custom membership

I want use custom membership and custom role providers. I have this classes:
public class CustomRoleProvider : RoleProvider
{
//override methods
}
public class CustomMembershipProvider : MembershipProvider
{
//override methods
}
I want set web.config, Is correct this code?
<membership defaultProvider="CustomMembershipProvider">
<providers>
<clear />
<add name="CustomMembershipProvider" type="Login1.Code.CustomMembershipProvider, Login1, Version=1.0.0.0, Culture=neutral" connectionStringName="LoginDB1Entities" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="CustomRoleProvider">
<providers>
<clear />
<add name="CustomRoleProvider" type="Login1.Code.CustomRoleProvider" connectionStringName="LoginDB1Entities" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" writeExceptionsToEventLog="false" />
</providers>
</roleManager>
Because when I go to the ASP.NET Configuration, and Security tab, but get this message:
There is a problem with your selected data store. This can be caused by an invalid server name or credentials, or by insufficient permission. It can also be caused by the role manager feature not being enabled. Click the button below to be redirected to a page where you can choose a new data store.
The following message may help in diagnosing the problem: The method or operation is not implemented.
Issue here seems to be originating from your connectionStringName property.
make sure you define/add the connection string in your Web.config's <connectionStrings> section
<connectionStrings>
<add name="LoginDB1Entities" ... />
</connectionStrings>
Also, if you ahve added already as above, then make sure you are using the correct settings.
First check where exactly your database is? Find out which instance of the SQL Server is the database of your application using. Modify the connection string to point to that instance.
The method or operation is not implemented
This is the message get if you throw NotImplementedException without any arguments.
The most obvious reason is that one of your custom providers has not implemented one of the expected methods. If you can get a stack trace, you'll see which one.
UPDATE in response to comment:
my custom membership is working in site
The membership and role providers contain methods for two purposes:
Methods needed at runtime for authentication (MembershipProvider) and authorization (RoleProvider). For example, at runtime a RoleProvider only uses the methods IsUserInRole and GetRolesForUser.
Methods needed to manage users (MembershipProvider), and roles / role membership (RoleProvider). These methods are needed if you want to manage your provider's data store using the ASP.NET Configuration and Security tab.
It's perfectly valid to create a provider that only provides the runtime functionality - a so-called "readonly" provider, in which case you'll have to provide some other outside mechanism for managing the provider's data store. For example, WindowsTokenRoleProvider is a readonly provider. But if you do this, you won't be able to manage your provider store using the ASP.NET Configuration and Security tab.
It appears you have failed to implement one or more of the management methods, and instead are throwing NotImplementedException.
Incidentally, NotImplementedException is not the best exception to throw for unsupported methods in a readonly provider. It should only normally used to indicate a method has not yet been implemented in a version under development.
If you don't ever intend to implement the method, it's better to throw NotSupportedException - or in the case of a provider, perhaps a ProviderException.

My ASP.NET 4 login stopped working...why?

I am working on an ASP.NET 4.0 C# project. The CreateUserWizard is working fine, but the login controls I built are always showing this message:
Your login attempt was not successful. Please try again.
This started happening after I changed the membership and connection string settings in machine.config to experiment, which I changed to default later i.e.:
Here's the connection string settings:
<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
And here is the membership section:
<membership>
<providers>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="LocalSqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression=""/>
</providers>
</membership>
Also, I have changed my default database to store my websites data to login controls default data i.e. ASPNEDB.mdf by writing two lines in every code behind of page
SqlConnection con = new SqlConnection("data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true");
SqlCommand cmd = new SqlCommand();
Even when I finish CreateUserWizard1 successfully and redirect to my homepage.aspx, where I have used default label of asp.net LoginName, the label is showing blank.
And if I manually put Label1 and type Label1.Text = HttpContext.Current.User.Identity.Name;, its still not working.
Will you please help me. I have to show this project to my college and not only that but my team will fail due to my EXPERIMENT.
There are several potential issues here:
You changed the machinekey in the web.config. If so, change it back. If you can't change it back then delete all the users in your table and recreate them. You're using a one way hash algorithm that requires the machinekey to hash the entered password for comparison.
You made changes to the connection string. Are you sure the database even has those user records in it? Next, did you happen to delete / recreate the database? If so those users are gone. See #1.
More to the point it's obvious you haven't put everything back like it was.
So, why are you getting login failed? Potential options are:
The database being accessed isn't the one you think it is.
The user truly doesn't exist in the database its looking at.
The user does exist but the password you are providing isn't the correct one.
The user exists and the password is correct, but the machinekey has changed and therefore the system can't hash it correctly.
Basically it's probably time to start over by clearing out your database and adding users into it again.

Access to web.config attributes (not appSettings)

given that I can add various attributes to the stock membership provider I assume I can do the same with my own provider implementation.
<add name="MyMembershipProvider" type="Portal.Infrastructure.MyMembershipProvider"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
[...] />
My question now: How do I access these values in the code? I understand that the ConfigurationManager can be used to access key value pairs in the appSettings section but this is different.
I don't know what section you trying to acces but genearl idea is that you can access WebConfig directly by:
Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);
// Get the object related to the <identity> section.
IdentitySection section = (IdentitySection)config.GetSection("system.web/identity");
Instead of IdentitySection put your section.

Problem creating users programmatically in ASP.net

For reference here is what my web.config and code look like:
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="MySqlConnection"
applicationName="/"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
passwordFormat="Hashed" />
</providers>
</membership>
VB code behind the fact:
Public Function Register(ByVal EncryptedName As String, ByVal EncryptedEmail As String) As String
Dim ret As String = ""
Try
Dim Provider As MembershipProvider = Membership.Providers.Item("SqlProvider")
Dim createStatus As MembershipCreateStatus
Dim newUser As MembershipUser = Provider.CreateUser(EncryptedName, Membership.GeneratePassword(8, 1), EncryptedEmail, "Your favorite color?", "RED", True, Guid.NewGuid, createStatus)
Select Case createStatus
Case MembershipCreateStatus.Success
ret = "The user account was successfully created!"
Case MembershipCreateStatus.DuplicateUserName
ret = "There already exists a user with this username."
Case MembershipCreateStatus.DuplicateEmail
ret = "There already exists a user with this email address."
Case MembershipCreateStatus.InvalidEmail
ret = "The email address provided is invalid."
Case MembershipCreateStatus.InvalidAnswer
ret = "The security answer is invalid."
Case MembershipCreateStatus.InvalidPassword
ret = "The password you provided is invalid. It must be seven characters long and have at least one non-alphanumeric character."
Case Else
ret = "There was an unknown error; the user account was NOT created."
End Select
Catch ex As Exception
Return "Server Error."
End Try
Return ret
End Function
For reference sake this is a webservice that we're using to allow users to register from our website and from desktop software. I don't know if it is the desktop software that is causing this problem. Right now I'm getting an exception on the create new user line. The exception says 'Login failed for 'DOMAIN/user' where DOMAIN is my work domain and user is my work login for my PC.
I've been looking around and found I needed to explicitly tell which provider to use (the provider checks out fine). I found a lot of samples where people simply used Membership.CreateUser but I found it wasn't loading the correct login.
I also tried playing with the authentication tag in the web.config.
The simple idea is to programmatically register new users through a webservice so it can be used with website and multiple in house desktop software applications.
Thanks for any help.
The membership provider is configured with a reference to a connection string. Have you confirmed it is a valid connection string? It sounds like your using the default one which will try to connect with integrated authentication. Also, the user being your login for your PC tells me either you're running from debug or IIS's application pool has an explicitly set identity.
That probably won't solve your problem, but, I wanted to offer what I could as I've had similar frustration in the past.

Resources