ASP Identity - AddToRoleAsync - asp.net

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 ?

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?

Best way to force user to log in before accessing my website

I'm getting started with Firebase and I would like to have a suggestion concerning the best way to force a user to be logged to use my website.
I'm building a very simple app but i have to guarantee that content can be displayed only to logged people
Thank you!
Use auth().onAuthStateChanged
https://firebase.google.com/docs/auth/web/start#set_an_authentication_state_observer_and_get_user_data
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
// ...
} else {
// User is signed out.
// ...
}
});
I assume you are using PHP to build your firebase website, in php there are session tokens that can be used to auto log in. once you got a session login you could use that to redirect them to the login page if they are not logged in. here a snip of code from one of my old college projects.
if(!isset($_SESSION['user_logged_in'])){
header("Location: ../login.php");
}else{
if($_SESSION['user_logged_in'] != true){
header("Location: ../login.php");
}
}
its been a while but this checks if I remember correctly the first line checks if there is no session token and the second line checks to see if that person is logged in. if either of this isn't true it will load the login page instead of the page they wanted and cause its all done in php they can't get around this. we put all this in an authentication template, I have uploaded the PHP file to google drive if you wish to example how logins are done, this is using an MYOB database so you will have to convert it but the code in here should be a good example.
https://drive.google.com/open?id=1_oKWU3LnpmfJg2pD5kHzYxFX2Ydl42e_
hope this helps

Xamarin Azure Facebook get user info

I've been searching on the best way to get information my azure auth from facebook.
My app is getting the authentication and the id of the user! I am not sure what code I need next in order to get the information.
So far I have this
if (authenticated)
{
var client = new HttpClient();
var fbUser = await client.GetAsync(Appurl+".auth/me");
var response = await fbUser.Content.ReadAsStringAsync();
var jo = JObject.Parse(response);
var userName = jo["'typ':'user_id'"].ToString();
}
So far all the answers have left me clueless
I just need this to return name email and other Items I want.
I am sure this is an Json Parsing the wrong issue but I am not sure.
Please help!!!
I just need this to return name email and other Items I want. I am sure this is an Json Parsing the wrong issue but I am not sure.
If you visit https://yourmobileapp .azurewebsites.net/.auth/me from browser, and login with your FaceBook account. Then you could get the Json structs as following. It is a JArray . So please have a try to use following code, it works correctly on my side.
var ja = JArray.Parse(response);
var id = ja[0]["user_id"];
Before that we need to add email scope on the Azure portal, about how to add email scope, please refer to the screenshot.

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?

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