Update just 'Comments' MembershipUser Property - asp.net

I am trying to update just the 'Comments' property in ASP. NET MembershipUser and want to leave all other property untouched. Here is my codes
MembershipUser userComments = Membership.GetUser(sUserName);
userComments.Comment = "Need Change Password";
Membership.UpdateUser(userComments);
It throws an expection 'The E-mail supplied already exists in the database for the application' at Membership.UpdateUser(userComments)
How can I just update only the 'Comments' without changing emails or any other properties?

Based on your comment, it is throwing configuration exception. You can ignore this validation by setting requiresUniqueEmail to false in your web.config.
<add name="AspNetSqlMembershipProvider"
....
requiresUniqueEmail="false"
....
/>
However it is possible that you have a duplicate email in your database and the framework doesn't know for which one you're trying to update Comment. So to get rid of the duplicate might be a better option.

Related

Easy way to secure connectionstring

So i remember that my teacher once taught us how to secure connectionstrings in web.config.
Unfortunately, now when i need to know it, i have forgotten all about it.
I have been looking around in here, and found some different questions regarding this, where all of which seemed to have a slightly complicated solution.
Im asking, because i remember that my teacher secured his password in the connectionstring with just a few signs/glyphs, instead of encrypting the entire string.
So my question is obviously how i can secure (doesn't have to be very strong) my connectionstring in one easy way.
you can try using flags in the connecction string as follows:
<add name="PSystem"
connectionString="Server=test;
Database=Dev;
User ID=#UserID#;
Password=#Password#;
Trusted_Connection=False;
Encrypt=True;"
providerName="System.Data.SqlClient" />
then you can have the encrypted user and password as follows:
<add key="DB_User" value = [Encrypted Username]>
<add key="DB_Password" value = [Encrypted Password]>
Then in code you just replace the flags:
string _connectionString = ConfigurationManager.ConnectionStrings["PSystem"].ConnectionString;
string user = Decrypt(ConfigurationManager.AppSettings["DB_User"]);
string password = Decrypt(ConfigurationManager.AppSettings["DB_Password"]);
_connectionString = _connectionString.Replace("##User##", user).Replace("##Password##", password);
For all above, thanks to Oscar Rivera answer as well. Hope this helps!

How to set the current user for WebPartManager?

From what I've been reading, the following code should first ensure that a MembershipUser record exists for "ArthurDent", then set "ArthurDent" as the current user, and finally assign his MembershipUser record to the variable mUser.
if (Membership.GetUser("ArthurDent") == null)
{
Membership.CreateUser("ArthurDent", "thisisapassword");
}
FormsAuthentication.SetAuthCookie("ArthurDent", true);
MembershipUser mUser = Membership.GetUser();
Instead, the variable mUser remains null.'
My goal is to programmatically set the current user to a valid record so that I can set a WebPartManager.DisplayMode on a page that started erroring out when I added BlogEngine to my web site.
This problem generally occurs when the application breaks a rule defined in the web.config file. For instance I ran your code in my local environment using Windows Authentication and CreateUser at first failed because the password string was of insufficient length. I padded the password with additional characters and was able to create user with the supplied code. Check the section to examine password prerequisites.
Upon first examination this looks like a configuration problem.
The answer is that BlogEngine actively suppresses the normal workings of Page.User.Identity, which Membership.GetUser() retrieves. When I replaced FormsAuthentication.SetAuthCookie with the following code from BlogEngine...
Security.AuthenticateUser("ArthurDent", "thisisapassword", true);
... it authenticated Arthur and logged him in.

custom authorization and page protection in asp.net

need to solve a custom authorization issue.
I already have four tables in my database named:
1. Usermaster
2.Roles
3.RoleMenu
4.Menu
I have implemented this and its working perfectly.
My only issue now is that an authenticated user can view an unauthorized page by simply entering the page url in the browser.
Any useful ideas apart from forms authentication and folder level access?
I had a project similar to this and i can't seem to find the code anywhere as it was quite awhile ago. I remember the premise though. What i did was i set up a key in the webconfig that had usernames allowed access in a pipedelimited string. Behind the code i would pull in that key as well as the user trying to access the page. I would then search the string and try and match the user. If a match was found the page would load, if a match wasn't found it would redirect them to a page telling them they didn't have access and who to contact to request access. I'll look for the code and edit if i find it.
EDIT
WebConfig
<appSettings>
<add key="Users" value="user1|user2|user3|..." />
</appSettings>
This piece goes above the
For the .aspx.vb page
Dim DomainUserName() As String = Request.ServerVariables("LOGON_USER").Split("\")
Dim UserName As String = DomainUserName(1)
Dim Users() As String = ConfigurationManager.AppSettings("Users").ToString.Split("|")
Dim isAllowedAccess As Boolean = False
For i As Integer = 0 To Users.Count - 1
If UserName = Users(i) Then
isAllowedAccess = True
Exit For
End If
Next
If isAllowedAccess = False Then
Response.Redirect("Default.aspx")
End If
Essentially our logins are domain\username so what i'm doing is extracting just the name using a split. I'm then populating the accepted users into an array splitting on the pipe and looping through them searching for a match. when the match is found it allows them access, if a match isn't found they are redirected back to the home page.

Change error message for locked out user in PasswordRecovery control

I use the ASP.NET PasswordRecovery control in combination with the standard membership provider. A locked out user gets the confusing error message
We were unable to access your information. Please try again.
I want to change this message, but find no way. The properties XXXFailureText especially GeneralFailureText contain over strings. There seems to be a hidden text used for this special kind of error I can't change using a property.
This was causing me a headache too, until I tried this. I added code to the VerifyingUser event to set the UserNameFaileurText if the user was locked out and it worked great, that is the error message was exactly what I wanted it to be.
protected void PasswordRecovery1_VerifyingUser(object sender, LoginCancelEventArgs e)
{
MembershipUser membershipUser = Membership.GetUser(PasswordRecovery1.UserName);
if (membershipUser != null && membershipUser.IsLockedOut)
{
PasswordRecovery1.UserNameFailureText = string.Format("<span style='font- size:larger'>Your account has been locked. Please contact<br/>your <a href='mailto:webmanager#aaa.co.uk?subject=Locked Account - {0}'>system administrator</a>.</span>", PasswordRecovery1.UserName);
}
}
Are you using a custom membership provider? This error can be cause by a partially implemented membership provider.
You also need to check you web.config settings. make sure that something like this is set:
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false"
As well as check they your mailsettings/smtp section is setup properly with a 'from' email address.
<mailSettings>
<smtp from="noreply#mysite.com">
<network host="mysite.smtp.server" port="25"/>
</smtp>
</mailSettings>
or set the 'from' in PasswordRecovery
<asp:PasswordRecovery runat="server">
<MailDefinition From="passwordrecovery#mysite.com">
</MailDefinition>
</asp:PasswordRecovery>
btw, your specified error message is the default UserNameFailureText. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.passwordrecovery.usernamefailuretext.aspx
If all else fails, you could hijack the events and cancel them, then show your own error message. Specially the UserLookupError and the other *Error events. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.passwordrecovery_events.aspx
In the properties window of the control there is a field for the text displayed that you can change

Can I configure the ResetPassword in Asp.Net's MembershipProvider?

I have an C# asp.net app using the default Sql MembershipProvider. My web.config has a few settings that control how I'm using this Provider:
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresUniqueEmail="true"
passwordFormat="Hashed"
minRequiredPasswordLength="5"
The problem I'm running into is that when people reset their passwords, it seems the ResetPassword() method returns a password that is longer than I want and has characters that can be confusing (l,1,i,I,0,O). Furthermore, I'm sending my users an email with a plain-text message and an HTML message (I'm using MailMessage with AlternateViews). If the password has unsafe HTML characters in it, when the email clients render the HTML text the password might be different (e.g. the %, &, and < aren't exactly HTML safe).
I've looked over the "add" element that belongs in the web.config, but I don't see any extra configuration properties to only include certain characters in the ResetPassword() method and to limit the password length.
Can I configure the ResetPassword() method to limit the password length and limit the character set it is choosing from?
Right now I have a workaround: I call ResetPassword() to make sure the supplied answer is correct, and then I use a RandomPassword generator I downloaded off the internet to generate a password that I like (without ambiguous characters, HTML safe, and only 8 characters long) and then I call ChangePassword() to change the user's password after I've already reset it.
My workaround seems kludgy and I thought it would be better to configure ResetPassword() to do what I want.
Thank you~!
ColoradoTechie
I don't believe you can do anything to "configure" the ResetPassword() call. You could write your own provider that changes how the ResetPassword() works.
This link describes the same tactic you seem to be doing already....
Staying with your work around/hack may be the simplest way to go. :-)
However, if you want to learn more on how to create your own provider check out these links.
http://www.asp.net/learn/videos/video-189.aspx
http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx
http://www.devx.com/asp/Article/29256/0/page/3
http://www.15seconds.com/issue/050216.htm
Using the GeneratePassword method ensures at least that the created password fulfills your setup for MinRequiredPasswordLength and MinRequiredNonAlphanumericCharacters. I am doing something like this:
// aUser is of class MembershipUser
string aTempPassword = aUser.ResetPassword();
string aNewPassword = Membership.GeneratePassword(
Membership.MinRequiredPasswordLength,
Membership.MinRequiredNonAlphanumericCharacters);
aUser.ChangePassword(aTempPassword, aNewPassword);
Well, that's only 50% of what you want since you cannot control the character set used for the final password.
(Actually that's also from my viewpoint the more important aspect - especially if you have users who need 10 minutes and 3 support calls to hit the key combination of a curled bracket successfully and don't have a clue what a clipboard is. ResetPassword can make you one of the most hated persons.)
I know this has already been answered but I wanted to add my 2 cents since I came across this issue today.
The SQLMembershipProvider class exposes
public virtual string GeneratePassword()
which is called by ResetPassword. Therefore you can simply extend the SQLMembershipProvider class and implement your own version of GeneratePassword.
Note that doing so will require you to update the membership provider entry in your web.config to use your new membership provider class:
<membership>
<providers>
<add type="My.Namespace.MyCustomSqlMembershipProvider" ... />

Resources