ASP.NET Identity : Cannot sign-in existed user - asp.net

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?

Related

Blazor Server - Refresh User Roles without Logging Out?

Say you're using the built in AspNetCore Identity implementation.
To access some data a User must have the "CanFetchData" role. If they don't, a "Get Access" button is displayed which upon being clicked gives the User the Role and now they can see the data. Without Loggin Out. That's all I'm trying to do.
So onclick we:
var authState = await authenticationStateTask;
var currUser = await UserManager.GetUserAsync(authState.User);
await UserManager.AddToRoleAsync(currUser, "CanFetchData");
And now the Role is in the db. But the only way to update the view is to fully logout.
I've tried using StateHasChanged(); and SignInManager.RefreshSignInAsync(currUser) and a number of other approaches.
I realized that if I add the Claim directly it will update properly:
var newIdentity = new ClaimsIdentity();
newIdentity.AddClaim(new Claim(ClaimTypes.Role, "CanFetchData"));
authState.User.AddIdentity(newIdentity);
But is there no built in function to just refresh from the db?

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.

ASP Identity - AddToRoleAsync

I have a problem using the Microsoft AddToRoleAsync() function.
For usernames where there is a hyphen in them I cannot get it to work successfully. For example:
var user = new ApplicationUser();
var email = "name-surname#company.com";
user = await userManager.FindByEmailAsync(email);
await userManager.AddToRoleAsync(user.Id, "Admin");
I don't get an error thrown, the user just doesn't get added to the role and an entry never appears in the AspNetUserRoles.
However, as soon as I remove the hyphen in the email / username the AddToRoleAsync() works perfectly, which seems strange as this function takes an Id and role name.
We have the same value for both the email and username field.
Can anyone help ?

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

Querying membership database with the membership api

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().

Resources