Querying membership database with the membership api - asp.net

I am using membership api to fetch the user password and email.
I have got this code:
MembershipUser currentUser = Membership.GetUser();
UserPasssword.Text = currentUser.GetPassword(); //Null exception
I need to check the user at the login. The problem is that the user isnt login. So I thought to find a way to fetch the user password or email with the membership api and not through the a database query. Is there a way to do it? or do I have to resort to a database query?
Remember that the user isnt logged in .. .. So the result will be null point exception each time on the currentUser object..
How can check his email with the membership api and then use a redirection:
if (currentUser.Email == LoginEmail.Text && currentUser.GetPassword() == hash)
{
FormsAuthentication.RedirectFromLoginPage(currentUser.UserName, false);
}
else
{
LoginFail.Text = "Email or Password havent been incorrect.";
}

If you're just trying to log the user in, you'd be better off letting membership handle it via the Validate User method.

To get the Email and Password of a user, you can use Membership.GetUser(username). This method returns a MembershipUser object that you can query Email and GetPassword().

Related

AcquireTokenAsync returning null for User.DisplayableId

I’m developing a Xamarin app that uses Azure AD B2C and I’m having some trouble getting data from any of the providers.
Even though I have LinkedIn, Google, Microsoft, Facebook, and Twitter setup as Identity Providers, and they appear to be configured properly, the only data returned is User.IdentityProvider. Both User.Name and User.DisplayableId are null. This happens for all of the providers.
Here is my call to AcquireTokenAsync:
var result = await App.AuthenticationClient.AcquireTokenAsync(Constants.Scopes, user, UIBehavior.SelectAccount, string.Empty, null, Constants.Authority, App.UiParent);
I have my application claims selected:
The login succeeds on every provider, but I don't get email addresses back like I need.
With help from a friend, I discovered that while the values in the User field are returned using Azure AD, the response from an Azure AD B2C call populates the IdToken field instead.
A bit more sleuthing turned up this to be a serialized JwtSecurityToken object. That led me to the following code:
var displayableId = ""; // result.User.DisplayableId;
var token = new JwtSecurityToken(result.IdToken);
foreach (var claim in token.Claims)
{
if (claim.Type == "emails")
{
displayableId = claim.Value;
}
}
Now displayableId contains the user's email address.

Need to enter more data for user sign up in Firebase

I'm new to Firebase. I was looking at the Firebase documentation and it seems good. But one thing I've noticed is that when I register/sign up my users, I can only get their email ID and password.
However, for my app, I need my users to enter more details like name, address, phone, and some other details. How can I do this?
I thought maybe I can use the real time database, but then I didn't know how to match the users with their respective details from the realtime database. Please give me some ideas on how to do this.
You're right.
In order to save some user data, you will have to use Realtime Database. There are few properties you can assign to user like email, photoURL, displayName but for more than that you have to use database.
Hope it helps, here is a way I am doing it:
I created "users" node in database and every time new user registers, new entry with his uid gets inserted. Check screenshot below:
So every time you need to get user data, just call child at "users" node with given "current user uid".
On Success of registration , get all the details and update/create the information in firebase database.
final String emailId = mEditTextEmail.getText().toString() ;
String password = mEditTextPassword.getText().toString() ;
firebaseRef.createUser(emailId, password, new Firebase.ValueResultHandler<Map<String,Object>>() {
#Override
public void onSuccess(Map<String, Object> stringObjectMap) {
User user = new User();
user.setUid(stringObjectMap.get("uid").toString());
user.setEmail(emailId);
user.setProfileStatus(User.NEW);
firebaseRef.child("Users").child(user.getUid()).setValue(user);
mProgressBar.setVisibility(View.GONE);
Intent intent = new Intent(SignupActivity.this,LoginActivity.class);
intent.putExtra("email",mEditTextEmail.getText().toString());
startActivity(intent);
Toast.makeText(getBaseContext(),"You are Successfully Registered in",Toast.LENGTH_SHORT).show();
Toast.makeText(getBaseContext(),"Login to continue..",Toast.LENGTH_SHORT).show();
}

ASP.NET Identity : Cannot sign-in existed user

I use ASP.NET Identity 2 in an MVC 5 project and there are some users in AspNetUsers table. Although these users have been created and validated, it is impossible to retrieve any of them bu using:
var user = await UserManager.FindByNameAsync(model.Email);
Please note that I used email addressed for UserName as Email fields and it is ok to use email address for retrieving users.
On the other hand, I can retrieve the users by:
ApplicationUser user = db.Users.FirstOrDefault(m => m.Email == model.Email);
But, I cannot make sign-in the user with the following code and the result is always Failure.
var result = await SignInManager.PasswordSignInAsync(user.Email,
model.Password, model.RememberMe, shouldLockout: false);
Any idea to fix the problem?

How to check password manually in Asp.Net identity 2?

This might actually be more of a conceptual question. In Asp.Net Identity the PasswordHasher generates a different hash for the same string every time you do:
new PasswordHasher.HashPassword("myString");
Now if for some reason I need to manually compare a user's input to the password saved in the database, I will most probably get a different string when I hash the user's entered password, than the one that is stored in the database.
Can someone please explain this to me? Shouldn't hashing the same string result in the same hash and if not, how does Identity itself realize that two different hashes are in fact the same?
PasswordHasher generates different hashes each time because it uses salting technique. This technique secure the hashed password against dictionary attacks. By the way you could use following code to manually verify the password:
if(PasswordHasher.VerifyHashedPassword("hashedPassword", "password")
!= PasswordVerificationResult.Failed)
{
// password is correct
}
var user = _userManager.Users.SingleOrDefault(p => p.PhoneNumber == model.PhoneNumber);
if (user == null)
{
return RedirectToAction(nameof(Login));
}
var result1 = _userManager.PasswordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password);
if (result1 != PasswordVerificationResult.Success)
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}

WebSecurity.ChangePassword returning FALSE value

I can't figure out why my WebSecurity.ChangePassword is not working. Here's the piece of code I'm working on.
if (WebSecurity.ChangePassword(USER, oldpass, password)) {
Response.Redirect("~/SuperAdmin");
return;
}else {
ModelState.AddFormError(USER);
// I put the each WebSecurity.ChangePassword parameter to this parameter to check whether
//each parameter valid or not (print it out)
}
and for each parameter of WebSecurity.ChangePassword, I retrieve it from the database as follows
if(IsPost){
Validation.RequireField("email", "Masukkan email");
Validation.RequireField("password", "Masukkan Password");
Validation.RequireField("userid", "user ID tidak ada!");
email = Request.Form["email"];
password = Request.Form["password"];
userId = Request.Form["userId"];
if(Validation.IsValid()){
var db = Database.Open("StarterSite");
var updateCommand2 = "UPDATE UserProfile SET Email=#0 WHERE UserId=#1";
db.Execute(updateCommand2, email,userId);
var USER = db.QueryValue("SELECT a.Email FROM UserProfile a, webpages_Membership b WHERE a.UserId=b.UserId AND a.UserId= #0", userId);
var oldpass = db.QueryValue("SELECT Password FROM webpages_Membership WHERE UserId = #0", userId);
Can anyone tell me what seems to be the problem here? Thanks in advance
The WebPages Membership has everything built you do not need to get the users email address and password (I am guessing the email address is the username right?) The ChangePassword method takes 3 arguments. which is UserName, CurrentPassword, NewPassword.
The reason your getting false is because your getting the old password from the database based on the users current Id, but the old password does not match the users current password because old one is encrypted and you're not encrypting the one they submit (in fact you don't even have a field for them to enter their current password).
The WebPages Membership provider will do all the updating you do not need open the database and update the users password, the weird thing you're doing is telling the user to enter a new password but not asking for the current one! Here see this for more information:
http://www.thecodingguys.net/reference/asp/websecurity-changepassword
Make sure the user you are trying to change password for is not LockedOut. You can check it by this
select * from aspnet_membership
where
IsLockedOut = 1

Resources