Create User using Membership.CreateUser - asp.net

I used the following to create new users using SqlMembershipProvider. While trying to create new users using CreateUserWizard, it throws exception 'The username is already in use' even though there is no any user exists and also new row is creating successfully with this username and password in my table.
MembershipUser newUser = Membership.CreateUser(createWizard.UserName, createWizard.Password);
If i hard code the value of username and password no exception occurs.
Can any one tell me the reason why it throws the exception when using CreateWizard?

MembershipCreateStatus status;
var user = Membership.CreateUser(login, password, email, null, null, true, out status);
Try this.

Check in your Membership.dbo database if this user exists.
SELECT *
FROM aspnet_Users
WHERE (UserName = 'YourUserName')

Related

How do I log a user back in after change of Email/Username? - Asp.net/VB.Net

I found this code on a site which was written for me and works, and I'm trying to use it on a new site. The code checks that a emailAddress doesn't already exist when a user edits their account details, and because the emailAddress is also used as the underlying .NET membership username it needs to change that too. So far I've managed to get it to change the email address in tblAccounts which is done with this call:
acc.UpdateUsername(txtEmailAddress.Text, lblEmailAddress.Text)
Then it needs to check if the user changing the email is the logged in user and re-log them back in. This doesn't seem to work as I get this error from the siteMaster when it tries to redirect to the homepage:
System.NullReferenceException: Object reference not set to an instance of an object.
The error is caused in the siteMaster when it tries to check messages for logged in user and it flags up the last line of this as where the error occurs:
If HttpContext.Current.User.Identity.IsAuthenticated Then
hypSettings.visible=true
Dim counter As Integer = messaging.CheckUnreadMessages(Membership.GetUser.ProviderUserKey)
It therefore looks like the email address is being updated where it should, but the site isn't logging the user back in correctly. As I say, it works on the site where I took the code from and there isn't much difference between the sites, but I don't understand memberships and cookies too well so I'm not sure if something needs altering elsewhere?
Here's the code for changing the users email address:
'Check if the Role has been changed
Membership.ApplicationName = "/OCBS"
Dim userID As Guid = Guid.Parse(Request.QueryString("aID"))
Dim usr As MembershipUser = Membership.GetUser(userID, False)
'Now check if the email address has been changed, because the email address is used for the username then the underlying .NET membership username needs changing
If txtEmailAddress.Text <> lblEmailAddress.Text Then
'Email has been changed, update the username for this user
Dim acc As New accounts(Guid.Empty)
acc.UpdateUsername(txtEmailAddress.Text, lblEmailAddress.Text)
'Check if the user changing the email is the logged in user and re-log them back in
If User.Identity.Name = lblEmailAddress.Text Then
'FormsAuthentication.SetAuthCookie(txtEmailAddress.Text, False)
Response.Cookies.Clear()
Dim expiryDate As DateTime = DateTime.Now.AddDays(100)
Dim ticket As New FormsAuthenticationTicket(2, txtEmailAddress.Text, DateTime.Now, expiryDate, True, [String].Empty)
Dim encryptedTicket As String = FormsAuthentication.Encrypt(ticket)
Dim authenticationCookie As New HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
authenticationCookie.Expires = ticket.Expiration
Response.Cookies.Add(authenticationCookie)
End If
End If
Oooh, I've managed it.. I added this..
Session.Abandon()
FormsAuthentication.SignOut()
after line: Response.Cookies.Clear()

How to access multiple tables from a SELECT FROM in ASP.NET with SQL Server?

I have this project I am working on for an assignment, and I have a question working with ASP.NET and SQL Server. I have a login page that kinda works, but there are two tables that I need to get data from - users (subscribers) and admin page but am unsure how to access both of them as I can only access one.
public void login(Object src,EventArgs e)
{
get_connection();
try
{
connection.Open();
command = new SqlCommand("SELECT * FROM subscribers WHERE Email = #Email AND Password = #Password", connection);
command.Parameters.AddWithValue("#Email", loginName.Text);
command.Parameters.AddWithValue("#Password", loginPass.Text);
//command = new SqlCommand("SELECT * FROM admin WHERE Email =#Email and Password = #Password", connection);
//command.Parameters.AddWithValue("#Email", loginName.Text);
//command.Parameters.AddWithValue("#Password", loginPass.Text);
reader = command.ExecuteReader();
I commented out the admin part because when I include it, only admin username and password is accepted and not subscribers. What would I need to do to fix this?
The "admin part" causes you to only get records from the admin table because you're destroying and recreating your SqlCommand object. You'll need to create a new command in a different variable and read from it separately. There are ways to get multiple recordsets in the same call but I don't recommend it in this case.
That out of the way... Normally I'd expect to see a single users table with permissions/roles granted elsewhere. Consider something like the out of the box ASP.NET membership provider to take care of these implementation details for you:
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-use-the-aspnet-membership-provider

How do I trigger a reset password?

I work in Microsoft .NET 4.0 environment.
In my application I enable the user to get new automatic password.
So I use in my .cs file the method:
MembershipUser user = Membership.GetUser();
user.ResetPassword();
I want to trigger on reset Password, means: when the password is changed to the automatic
one, an email will be sent to the user's email address with the new password (that is returned from user.ResetPassword()).
I use standard Membership DB tables.
I wrote the following trigger:
CREATE TRIGGER MembershipChangePass ON aspnet_Membership
AFTER UPDATE,DELETE
AS
BEGIN
DECLARE #user uniqueidentifier
DECLARE #email nvarchar(256)
SELECT #user = (SELECT UserId FROM UPDATED)
SELECT #email =(SELECT LoweredEmail FROM aspnet_Membership
WHERE #user=UserId)
EXEC xp_sendmail #email, ???
END
GO
The problem is how do I get the ??? - the new automatic password I created by
the method: user.ResetPassword();
Can I define the TRIGGER to be used only with user.ResetPassword(), and not with other
methods (like: (user.ChangePassword(...))?
Maybe there is another simple way to trigger reset password?
Thank you.
The ResetPassword() method returns the new password which you can grab and send to the user
string newPassword = user.ResetPassword();
string toAddr = "user email here";
string subject = "Password reset notification";
string body = "Your new password is "+newPassword;
//mail.Send(fromAddr, toAddr, subject, body);

What is happening when ASP.NET MVC 3 Accounts Scaffolding calls Membership.Createuser?

I am an asp mvc 3 noob trying to modify the user account scaffolding to hold more information. When users create an account, I want to add additional information like their full name and start date--not just their username/pw. I am going to store this added info in an Employees table in the DB.
I see the line of code in the AccountController that creates the account after the user types in input to the form.
Membership.CreateUser(model.UserName, model.Password, model.Email, Nothing, Nothing, True, Nothing, createStatus)
It seems like this line calls a stored procedure in SQL server. It seems like the most likely stored procedure is aspnet_Membership_CreateUser. But this stored proc has 13 parameters, and the code above passes 8 parameters.
What stored procedure is called by the VB code shown above (membership.createuser...)?
Why don't aspnet_Membership_CreateUser and Membership.CreateUser have the same number of parameters?
How do I modify the create user code/stored procedure to add employee information into the EmployeeTable based on info from the registration form, and then add a link between the user account and the Employee record? In general, the idea would be to add the employee info as additional parameters to the stored proc and then have the stored proc do the inserts/add the ids, but where exactly do I look to do this?
The code will run the aspnet_Membership_CreateUser stored procedure
The Membership.CreateUser is overloaded, and will put default values for parameters that would not have been provided. For example, if you call CreateUser with just the username and password, all the other parameters will be defaulted, e.g. IsApproved will be true. >>When typing in CreateUser, you should see the overload options. You can look at the code in "C:\Windows\Microsoft.NET\Framework\v4.0.30319\system.web.dll" using a tool like Just Decompile
There are different ways of storing additional data. Look at this one. I prefer linking the tables by UserId/Email address, and when creating a user, I call the CreateUser, and if its successful, then save the additional data (which is a slight variation of the method described in that tutorial). You can also modify/extend the whole membership provider, see this link (Implementing a Membership Provider) or this video tutorial
I can't answer your other questions, but here is the code I use the extend the user registration to contain more date (using a profile table, not the profile provider):
'
' POST: /Account/Register
<HttpPost()> _
Public Function Register(ByVal model As RegisterModel) As ActionResult
If ModelState.IsValid Then
' Attempt to register the user
Dim createStatus As MembershipCreateStatus
Dim MembershipUser = Membership.CreateUser(model.UserName, model.Password, model.Email, Nothing, Nothing, True, Nothing, createStatus)
If createStatus = MembershipCreateStatus.Success Then
Dim providerKeyObject = MembershipUser.ProviderUserKey
Dim providerKeyGuid = MembershipUser.ProviderUserKey
' update profile entity
Dim db As UserProfileDbContext = New UserProfileDbContext
Dim profile As New UserProfile
profile.UserId = providerKeyGuid
profile.IsCompanyOwner = True
profile.CompanyId = model.Company
profile.BlogId = model.Blog
profile.IsCompanyOwner = model.IsCompanyOwner
profile.IsBlogOwner = model.IsBlogOwner
db.UserProfiles.Add(profile)
db.SaveChanges()
FormsAuthentication.SetAuthCookie(model.UserName, False)
' send email
' TODO: fix error on send
Call New EmailController().VerificationEmail(model).Deliver()
Return RedirectToAction("Index", "Home")
Else
ModelState.AddModelError("", ErrorCodeToString(createStatus))
End If
End If
' If we got this far, something failed, redisplay form
Return View(model)
End Function

ASP.NET Impersonation design

This is my ASP.NET authentication operation.
private void LoginButton_Click(Object sender,
EventArgs e)
{
string userName = txtUserName.Value;
string password = txtUserPass.Value;
if (ValidateUser(txtUserName.Value, txtUserPass.Value))
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(3), chkPersistCookie.Checked,
userName + "#ticket");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
string strRedirect;
strRedirect = Request["ReturnUrl"];
if (strRedirect == null)
strRedirect = "MyAccount.aspx";
Response.Redirect(strRedirect, true);
}
else
Response.Redirect("logon.aspx", true);
}
I have User table in my db where all credentials are saved. Using ValidateUser method I am doing credentials validation. Also I have three type of users: Member, Moderator and Administrator. Each type of members has unique functionality. Lets say I have A, B and C T-SQL stored inside in my db.
What should I to to let for:
Member execute only A query.
Moderator execute A and B.
Administrator execute A,B and C.
Of course, I can manage execution from Web app, but I am not sure how safe it is. Technically I can execute similar query outside of App, which gives access to all db data. I want somehow combine Web App login and Db access as well.
Thanks!
If these queries are going to come from the web app, I think you would want to manage the code side that invokes the procedures.. you could maintain a list of urls in your database, assign roles, and give these roles access to specific urls. These urls would dictate what queries a user could execute...
then in your code you could assign custom attributes to limit access to them....
http://msdn.microsoft.com/en-us/library/ff647396.aspx

Resources