asp .net 4.0 membership error - asp.net

Please help me for this issue.
I have used asp .net membership. while creating new user using asp .net membership using below code. i am getting membership provoder error. can anyone tell me the solution for
this.
MembershipCreateStatus status;
//MembershipUser u = Membership.CreateUser(username, password, email, question,
// answer, true, out status);
MembershipUser u = Membership.CreateUser(username, password, email, question,
answer, true, out status);
if (u == null)
{
throw new MembershipCreateUserException(GetErrorMessage(status));
}
return u;
i have properly set web.config file. please tell me if i am missing anything. here is my web.config file membeship tag. and my database is mysql :
add name="MySQLMembershipProvider"
enablePasswordRetrieval="true"
autogenerateschema="false"
type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web, Version=6.3.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"
connectionStringName="LocalMySqlServer"
applicationName="/"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
passwordFormat="Clear"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
writeExceptionsToEventLog="false"
This is my error :MembershipCreateStatus.ProviderError

MembershipCreateStatus status;
Membership.CreateUser(username, password, email, question,
answer, true, out status);
if (status == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(username, false);
// Redirect to page
}
else
{
//get the error message here
return ErrorCodeToString(createStatus);
}
// if you get to here, throw an exception!
private static string ErrorCodeToString(MembershipCreateStatus createStatus)
{
// See http://go.microsoft.com/fwlink/?LinkID=177550 for
// a full list of status codes.
switch (createStatus)
{
case MembershipCreateStatus.DuplicateUserName:
return "User name already exists. Please enter a different user name.";
//add the rest of the error codes here....

Related

LDAP Server is not available

I am using LDAP for User Authentication in MVC.My code goes below as follows:
public ActionResult Login(LoginViewModel model, string returnUrl)
{
bool validation;
try
{
LdapConnection ldc = new LdapConnection(new LdapDirectoryIdentifier((string)null, false, false));
NetworkCredential nc = new NetworkCredential(model.UserName, model.Password, "XXXXXXX");
ldc.Credential = nc;
ldc.AuthType = AuthType.Negotiate;
ldc.Bind(nc); // user has authenticated at this point, as the credentials were used to login to the dc.
validation = true;
return RedirectToAction("Index", "Home");
//validation = true;
}
catch (LdapException)
{
validation = false;
}
return View(model);
}
but i am getting an error as "LDAP server not available"
Web.Config:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="10"/>
</authentication>
<membership defaultProvider="AspNetActiveDirectoryMembershipProvider">
<providers>
<clear />
<add name="AspNetActiveDirectoryMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider,System.Web, Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ADConnectionString"
attributeMapUsername="sAMAccountName" />
</providers>
</membership>
<add name="ADConnectionString" connectionString="LDAP://XXXXXXX:389/DC=XXXX,DC=XXXX" />
You did not set the path to the LDAP server (currently it is null)
LdapConnection ldc = new LdapConnection(
new LdapDirectoryIdentifier((string)null, false, false)
);
To debug, get rid of try..catch and see where exactly the error comes from. You might need to verify the path with your network administrator or use any tool like LDAP Browser where you could see if path and credentials would work.
Also, make sure that the way you want to authenticate is correct. If this is an intranet application then it might be that you could setup integrated Windows authentication which will not require any custom login process and can be configured on IIS.

Membership.CreateUser should fail but doesn't

I'm creating users for test purposes, using :
string username = ...
string password = ...
string email = "******** not a valid email address! *********";
MembershipUser NewUser = Membership.CreateUser(userName, password, email, "no question", "no answer", true, out createStatus);
if (NewUser == null)
{
switch (createStatus)
{
case MembershipCreateStatus.DuplicateUserName:
throw new Exception("There already exists a user with this username.");
case MembershipCreateStatus.InvalidEmail:
throw new Exception("There email address you provided in invalid.");
case MembershipCreateStatus.InvalidPassword:
throw new Exception("The password you provided is invalid. It must be seven characters long.");
default:
throw new Exception("There was an unknown error; the user account was NOT created.");
}
}
When this gets executed, a new user will get created, it doesn't fail with NewUser==null, MembershipCreateStatus.InvalidEmail, which is what I would expect.
Any idea why?
Here's the membership section from config if that has a bearing, although I don't see how:
<membership defaultProvider="myProvider">
<providers>
<add
name="myProvider"
applicationName="/"
connectionStringName="myconnectionsString"
enablePasswordRetrieval="true"
enablePasswordReset="true"
passwordFormat="Clear"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
minRequiredNonalphanumericCharacters="0"
type="System.Web.Security.SqlMembershipProvider"
/>
</providers>
</membership>
Thanks in advance!
From reflector this is the validation on email in SqlMembershipProvider
if (!SecUtility.ValidateParameter(ref email, this.RequiresUniqueEmail, this.RequiresUniqueEmail, false, 0x100))
{
status = MembershipCreateStatus.InvalidEmail;
return null;
}
internal static bool ValidateParameter(ref string param, bool checkForNull, bool checkIfEmpty, bool checkForCommas, int maxSize)
{
if (param == null)
{
return !checkForNull;
}
param = param.Trim();
return (((!checkIfEmpty || (param.Length >= 1)) && ((maxSize <= 0) || (param.Length <= maxSize))) && (!checkForCommas || !param.Contains(",")));
}
Looks like it doesn't care abut valid email or not, just that something is provided. You'll want to handle it from your client or override the SqlMembershipProvider.

Unexpected results when using UPN vs legacyUsername vs Shortname validation against AD

I'm using the AD Membership provider to validate user names and am having issues getting anything other than user#upnDomain.com to work.
Is it possible to get the other username formats to work?
Code
MembershipProvider domainProvider;
domainProvider = Membership.Providers["MyADMembershipProvider"];
if (domainProvider.ValidateUser("zzTest123", "pass"))
{
}
if (domainProvider.ValidateUser(#"PARTNERSGROUP\zzTest123", "pass"))
{
}
if (domainProvider.ValidateUser("zzTest123#company.com", "pass"))
{
}
if (domainProvider.ValidateUser("zzTest123#testfirm.com", "pass"))
{
// this is the UPN and the only one that works.
}
Web.config
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" name=".ADAuthCookie" timeout="10" />
</authentication>
<membership>
<providers>
<add name="MyADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="TestDomain1ConnectionString" />
</providers>
</membership>
Based on my testing the Membership provider only works with the UPN. To implement support for other types, override ActiveDirectoryMembershipProvider's ValidateUser function and add some variation of the following:
//
// Will validate UPN, shortname only, or domain prefixed (domain\user)
public bool IsAuthenticated( string usr, string pwd)
{
bool authenticated = false;
DirectorySearcher dseSearcher=null;
DirectoryEntry entry = null;
try
{
dseSearcher = new DirectorySearcher();
string rootDSE = dseSearcher.SearchRoot.Path;
entry = new DirectoryEntry(rootDSE, usr, pwd);
object nativeObject = entry.NativeObject;
authenticated = true;
}
catch (DirectoryServicesCOMException cex)
{
//not authenticated; reason why is in cex
}
catch (Exception ex)
{
//not authenticated due to some other exception [this is optional]
}
finally
{
dseSearcher.Dispose();
entry.Dispose();
}
return authenticated;
}
Be aware that the System.DirectoryServices.AccountManagement namespace will only validate the shortname, the UPN, but doesn't appear to validate DOMAIN\Username accounts.
The following code will throw an exception if a username is passed in DOMAIN\Username format
"LdapException: A local error occurred."
var ctx = new PrincipalContext(ContextType.Domain);
if (ctx.ValidateCredentials(username,password , ContextOptions.Negotiate))
{
}

How to Override createUser() ASP .NET Membership method to display custom error message?

How to Override createUser() Membership method to display custom error message when password check fails??
I Used the Web Site Administration Tool, which provides a wizard-like interface for creating new users. (To start this tool, click ASP.NET Configuration on the Website menu in the Microsoft Visual Studio)
Web.Config file:
<membership defaultProvider="MyMembershipProvider">
<providers>
<clear />
<add name="MyMembershipProvider" type="BlueDDApp.Controllers.MyMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" minRequiredPasswordLength="8" minRequiredNonalphanumericCharacters="0" passwordStrengthRegularExpression="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])|(?=.*[a-z])(?=.*[A-Z])(?=.*[!%,.;:])|(?=.*[a-z])(?=.*[0-9])(?=.*[!%,.;:])|(?=.*[A-Z])(?=.*[0-9])(?=.*[!%,.;:])$" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
Custom Membership class::
public class MyMembershipProvider : SqlMembershipProvider
{
public MyMembershipProvider()
{
//Membership.ValidatingPassword += new MembershipValidatePasswordEventHandler(OnValidatePassword);
ValidatingPassword += ValidatePassword;
}
/* public override MembershipUser CreateUser( string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
ValidatingPassword += ValidatePassword;
return base.CreateUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey, out status);
}*/
void ValidatePassword(object sender, ValidatePasswordEventArgs e)
{
Regex check = new Regex("^(?i)(?!.*" + e.UserName + ").*$");
if (!check.IsMatch(e.Password))
{
e.FailureInformation = new HttpException("blah blah");
e.Cancel = true;
}
}
}
If you are using asp:CreateUserWizard control, which I presume you are ( it will connect to a membership provider from your web.config ), then :
In Design mode, if you click on this control, in the top right corner you have an icon, sort of an arrow, and there you can choose "Customize Create User Step" option. This will transform the control, expanding it into a separate controls that are used inside. Now you can access error message ( Literal control ) and change it to display static message, or display dynamically changing messages from code.
You can also add events to the CreateUserWizard like CreatingUser, CreateUserError and CreatedUser which will let you customize the behavior and how the creation is being used even more.
Here is a great sample about custom MembershipUser:
Sample Membership Provider Implementation

Cannot create MembershipUser for custom MembershipProvider

I created a custom membership provider and am getting the following error trying to create a new "MembershipUser".
Could not load type 'MyTestApp.Membership.TestMembershipProvider' from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
I am running this from a Unit Test project, so I'm not sure if that's causing the issue, but I did include System.Web, System.Web.ApplicationServices as well as a reference to MyApp.Membership and MyApp.DataModels (Entity objects).
The error happens inside my "GetUser" function which is below, my configuration is also below.
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
try
{
AccountEntities db = new AccountEntities();
if ((providerUserKey is Guid) == false)
{
return null;
}
User user = (from u in db.Users
where u.UserId == (Guid)providerUserKey
&& u.Application.LoweredApplicationName == this.ApplicationName.ToLower()
select u).FirstOrDefault();
if (user != null)
{ // ERROR: Starts here, user object is correct, data is all there.
return new MembershipUser(this.ProviderName, user.UserName, (object)user.UserId, user.Email, user.PasswordQuestion, user.Comment, user.IsApproved, user.IsLockedOut, user.CreateDate, user.LastLoginDate, user.LastActivityDate, user.LastPasswordChangedDate, user.LastLockoutDate);
}
else
return null;
}
catch (Exception ex)
{
this.WriteToEventLog(ex, "Unable to get user from object '{" + ((Guid)providerUserKey).ToString() + "}'.", "Get User");
return null;
}
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="AccountEntities" connectionString="metadata=res://*/Account.AccountDataModel.csdl|res://*/Account.AccountDataModel.ssdl|res://*/Account.AccountDataModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source=&quotEDITED";Initial Catalog=CustomAuthentication;Persist Security Info=True;User ID=EDITED;Password=EDITED;MultipleActiveResultSets=True'" providerName="System.Data.EntityClient" />
</connectionStrings>
<system.web>
<membership defaultProvider="TestMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear/>
<add name="TestMembershipProvider" type="MyTestApp.Membership.TestMembershipProvider"
applicationName="/"
description="Membership Test"
enablePasswordReset="true"
enablePasswordRetrieval="true"
maxInvalidPasswordAttempts="3"
minRequiredNonAlphanumericCharacters="8"
minRequiredPasswordLength="8"
passwordAttemptWindow="30"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="true" />
</providers>
</membership>
</system.web>
</configuration>
I just noticed I missed the below part in the configuration
type="MyTestApp.Membership.TestMembershipProvider, MyTestApp.Membership"
Works now!

Resources